애플리케이션 이벤트 모니터링
개요
이 가이드 에서는 MongoDB Node.js 운전자 에서 모니터링 설정하다 하고 구성하는 방법을 학습 수 있습니다.
모니터링에는 애플리케이션 성능 관리 라이브러리와 함께 사용할 수 있는 실행 프로그램의 활동에 대한 정보를 수집하는 작업이 포함됩니다.
Node.js 운전자 모니터링하면 드라이버의 리소스 사용량 및 성능을 이해하고 애플리케이션 설계하고 디버깅할 때 정보에 입각한 결정을 내리는 데 도움이 될 수 있습니다.
이 가이드에서는 이와 같은 작업을 수행하는 방법애 대해 학습합니다.
이 가이드 코드에서 운전자 의 활동에 대한 정보를 사용하는 방법을 보여줍니다. 운전자 에서 이벤트를 기록 방법을 학습 Node.js 드라이버의 로깅 가이드 참조하세요.
이벤트를 모니터링합니다.
애플리케이션 에서 이벤트를 구독 Node.js 운전자 사용하여 이벤트를 모니터 할 수 있습니다.
이벤트 작동 중에 운전자 내에서 발생하는 모든 조치 입니다. Node.js 운전자 이러한 이벤트의 하위 집합을 수신하는 기능이 포함되어 있습니다.
Node.js 운전자 정의된 이벤트를 다음 카테고리로 구성합니다.
명령 이벤트
서버 검색 및 모니터링(SDAM) 이벤트
연결 풀 이벤트
다음 섹션에서는 각 이벤트 카테고리를 모니터링하는 방법에 대해 설명합니다.
명령 이벤트
명령 이벤트 는 MongoDB database 명령과 관련된 이벤트 입니다. 애플리케이션 에서 운전자 를 구독 하여 하나 이상의 명령 모니터링 이벤트에 액세스 할 수 있습니다.
MongoDB database 명령에 대해 자세히 학습 서버 매뉴얼의 데이터베이스 명령 가이드 참조하세요.
참고
명령 모니터링은 기본적으로 비활성화되어 있습니다. 명령 모니터링을 사용하려면 monitorCommands
옵션을 true
로 MongoClient
생성자에 전달합니다.
예시
다음 예시에서는 복제본 세트에 연결하고 MongoDB 배포에서 생성된 명령 모니터링 이벤트 중 하나를 구독하는 방법을 보여줍니다.
/* Subscribe to an event */ const { MongoClient } = require("mongodb"); // Replace the following with your MongoDB deployment's connection string const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri, { monitorCommands:true }); // Replace <event name> with the name of the event you are subscribing to const eventName = "<event name>"; // Subscribes to a specified event and print a message when the event is received client.on(eventName, event => console.log(event)); async function run() { try { // Establishes and verifies connection to the "admin" database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { // Closes the database connection on completion or error await client.close(); } } run().catch(console.dir);
이벤트 설명
다음 명령 모니터링 이벤트 중 하나를 구독할 수 있습니다.
이벤트 이름 | 설명 |
---|---|
| 명령이 시작될 때 생성됩니다. |
| 명령이 성공할 때 생성됩니다. |
| 명령이 실패할 때 생성됩니다. |
commandStarted
CommandStartedEvent { requestId: 1534, databaseName: "app", commandName: "find", address: 'localhost:27017', connectionId: 812613, command: { find: { firstName: "Jane", lastName: "Doe" } } }
commandSucceeded
CommandSucceededEvent { requestId: 1534, commandName: "find", address: 'localhost:27017', connectionId: 812613, duration: 15, reply: { cursor: { firstBatch: [ { _id: ObjectId("5e8e2ca217b5324fa9847435"), firstName: "Jane", lastName: "Doe" } ], _id: 0, ns: "app.users" }, ok: 1, operationTime: 1586380205 } }
명령 실패
CommandFailedEvent { requestId: 1534, commandName: "find", address: 'localhost:27017', connectionId: 812613, failure: Error("something failed"), duration: 11 }
서버 검색 및 이벤트 모니터링하기
Node.js 운전자 연결한 인스턴스 또는 클러스터 의 상태 가 변경될 때 토폴로지 이벤트(SDAM 이벤트라고도 함)를 생성합니다. 예시 를 들어, 운전자 사용자가 새 연결을 설정하거나 클러스터 새 프라이머리 노드 선택할 때 이벤트 생성합니다.
토폴로지 이벤트에 대해 자세히 학습 서버 매뉴얼의 복제 가이드 참조하세요.
다음 섹션에서는 애플리케이션에서 토폴로지 변경 사항을 기록하고 이러한 이벤트에서 제공된 정보를 탐색하는 방법을 보여 줍니다.
이벤트 구독 예시
애플리케이션 에서 하나 이상의 SDAM 이벤트를 구독 하여 액세스 할 수 있습니다. 다음 예시 복제본 세트 에 연결하고 MongoDB deployment 에서 생성된 SDAM 이벤트 중 하나를 구독 을 보여 줍니다.
/* Subscribe to SDAM event */ const { MongoClient } = require("mongodb"); // Replace the following with your MongoDB deployment's connection string const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri); // Replace <event name> with the name of the event you are subscribing to const eventName = "<event name>"; // Subscribes to a specified event and prints a message when the event is received client.on(eventName, event => { console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`); }); async function run() { try { // Establishes and verifies connection to the database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { // Closes the database connection on completion or error await client.close(); } } run().catch(console.dir);
이벤트 설명
다음 SDAM 이벤트 중 하나를 구독할 수 있습니다.
이벤트 이름 | 설명 |
---|---|
| 인스턴스에 대한 연결이 열릴 때 생성됩니다. |
| 인스턴스에 대한 연결이 닫힐 때 생성됩니다. |
| 인스턴스 상태가 변경될 때 생성됩니다(예: 세컨더리에서 프라이머리로). |
| 인스턴스에 연결을 시도하기 전에 생성됩니다. |
| 토폴로지의 모든 인스턴스 연결이 닫힌 후에 생성됩니다. |
| 새 프라이머리 투표 또는 mongos 프록시 연결이 끊어지는 등 토폴로지가 변경될 때 생성됩니다. |
| MongoDB 인스턴스에 |
|
|
| 특정 MongoDB 인스턴스에 대해 실행된 |
이벤트 문서 예시
다음 섹션에서는 각 유형의 SDAM 이벤트에 대한 샘플 출력을 보여줍니다.
serverDescriptionChanged
ServerDescriptionChangedEvent { topologyId: 0, address: 'localhost:27017', previousDescription: ServerDescription { address: 'localhost:27017', error: null, roundTripTime: 0, lastUpdateTime: 1571251089030, lastWriteDate: null, opTime: null, type: 'Unknown', minWireVersion: 0, maxWireVersion: 0, hosts: [], passives: [], arbiters: [], tags: [] }, newDescription: ServerDescription { address: 'localhost:27017', error: null, roundTripTime: 0, lastUpdateTime: 1571251089051, lastWriteDate: 2019-10-16T18:38:07.000Z, opTime: { ts: Timestamp, t: 18 }, type: 'RSPrimary', minWireVersion: 0, maxWireVersion: 7, maxBsonObjectSize: 16777216, maxMessageSizeBytes: 48000000, maxWriteBatchSize: 100000, me: 'localhost:27017', hosts: [ 'localhost:27017' ], passives: [], arbiters: [], tags: [], setName: 'rs', setVersion: 1, electionId: ObjectID, primary: 'localhost:27017', logicalSessionTimeoutMinutes: 30, '$clusterTime': ClusterTime } }
이 이벤트에서 ServerDescription
객체의 type
필드에는 다음 가능한 값 중 하나가 포함됩니다.
유형 | 설명 |
---|---|
| 알 수 없는 인스턴스 |
| 독립형 인스턴스 |
| Mongo 프록시 인스턴스 |
| 하나 이상의 서버가 이를 프라이머리 서버로 인식하지만, 아직 모든 인스턴스에서 확인되지는 않았습니다. |
| 프라이머리 인스턴스 |
| 세컨더리 인스턴스 |
| 중재자 인스턴스 |
| 자세한 내용은RSGhost 및 RSOther 사양 을 참조하세요. |
| RSGhost 및 RSOther 사양 참조 자세한 내용은 |
serverHeartbeatStarted
ServerHeartbeatStartedEvent { connectionId: 'localhost:27017' }
serverHeartbeatSucceeded
ServerHeartbeatSucceededEvent { duration: 1.939997, reply:{ hosts: [ 'localhost:27017' ], setName: 'rs', setVersion: 1, isWritablePrimary: true, secondary: false, primary: 'localhost:27017', me: 'localhost:27017', electionId: ObjectID, lastWrite: { opTime: { ts: [Timestamp], t: 18 }, lastWriteDate: 2019-10-16T18:38:17.000Z, majorityOpTime: { ts: [Timestamp], t: 18 }, majorityWriteDate: 2019-10-16T18:38:17.000Z }, maxBsonObjectSize: 16777216, maxMessageSizeBytes: 48000000, maxWriteBatchSize: 100000, localTime: 2019-10-16T18:38:19.589Z, logicalSessionTimeoutMinutes: 30, minWireVersion: 0, maxWireVersion: 7, readOnly: false, ok: 1, operationTime: Timestamp, '$clusterTime': ClusterTime }, connectionId: 'localhost:27017' }
serverHeartbeatFailed
ServerHeartbeatFailed { duration: 20, failure: MongoError('some error'), connectionId: 'localhost:27017' }
serverOpening
ServerOpeningEvent { topologyId: 0, address: 'localhost:27017' }
serverClosed
ServerClosedEvent { topologyId: 0, address: 'localhost:27017' }
토폴로지 열기
TopologyOpeningEvent { topologyId: 0 }
토폴로지 닫힘
TopologyClosedEvent { topologyId: 0 }
토폴로지 설명 변경됨
TopologyDescriptionChangedEvent { topologyId: 0, previousDescription: TopologyDescription { type: 'ReplicaSetNoPrimary', setName: null, maxSetVersion: null, maxElectionId: null, servers: Map { 'localhost:27017' => ServerDescription }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: null, heartbeatFrequencyMS: 10000, localThresholdMS: 15, options: Object, error: undefined, commonWireVersion: null }, newDescription: TopologyDescription { type: 'ReplicaSetWithPrimary', setName: 'rs', maxSetVersion: 1, maxElectionId: null, servers: Map { 'localhost:27017' => ServerDescription }, stale: false, compatible: true, compatibilityError: null, logicalSessionTimeoutMinutes: 30, heartbeatFrequencyMS: 10000, localThresholdMS: 15, options: Object, error: undefined, commonWireVersion: 7 } }
이 이벤트에서 TopologyDescription
객체의 type
필드에는 다음 가능한 값 중 하나가 포함됩니다.
유형 | 설명 |
---|---|
| 독립형 인스턴스 |
| 프라이머리가 있는 복제본 세트 |
| 프라이머리가 없는 복제본 세트 |
| 샤딩된 클러스터 |
| 알 수 없는 토폴로지 |
연결 풀 이벤트
연결 풀 운전자 MongoDB 인스턴스 사용하여 유지 관리하는 개방형 TCP 연결의 설정하다 입니다. 연결 풀은 애플리케이션 수행해야 하는 네트워크 핸드셰이크 횟수를 줄이고 애플리케이션 더 빠르게 실행 도움이 될 수 있습니다.
다음 섹션에서는 애플리케이션에서 연결 풀 이벤트를 기록하고 이러한 이벤트에서 제공된 정보를 탐색하는 방법을 보여 줍니다.
이벤트 구독 예시
애플리케이션에서 드라이버를 구독하여 하나 이상의 연결 풀 이벤트에 액세스할 수 있습니다. 다음 예시에서는 복제본 세트에 연결하고 MongoDB deployment에 의해 생성된 연결 풀 모니터링 이벤트 중 하나를 구독하는 방법을 보여 줍니다.
const { MongoClient } = require("mongodb"); // Replace the following with your MongoDB deployment's connection string const uri = "mongodb+srv://<clusterUrl>/?replicaSet=rs&writeConcern=majority"; const client = new MongoClient(uri); // Replace <event name> with the name of the event you are subscribing to const eventName = "<event name>"; // Subscribes to the event client.on(eventName, (event) => console.log("\nreceived event:\n", event) ); async function run() { try { // Establishes and verifies connection await client.db("admin").command({ ping: 1 }); console.log("\nConnected successfully!\n"); } finally { // Ensures that the client will close when you finish/error await client.close(); } } run().catch(console.dir);
연결 풀 모니터링 이벤트는 애플리케이션의 연결 풀 동작을 디버깅하고 이해하는 데 도움이 될 수 있습니다. 다음 예제에서는 연결 풀 모니터링 이벤트를 사용하여 풀에서 체크아웃된 연결 수를 반환합니다.
function connectionPoolStatus(client) { let checkedOut = 0; function onCheckout() { checkedOut++; } function onCheckin() { checkedOut--; } function onClose() { client.removeListener('connectionCheckedOut', onCheckout); client.removeListener('connectionCheckedIn', onCheckin); checkedOut = NaN; } // Decreases count of connections checked out of the pool when connectionCheckedIn event is triggered client.on('connectionCheckedIn', onCheckin); // Increases count of connections checked out of the pool when connectionCheckedOut event is triggered client.on('connectionCheckedOut', onCheckout); // Cleans up event listeners when client is closed client.on('close', onClose); return { count: () => checkedOut, cleanUp: onClose }; }
이벤트 설명
다음 연결 풀 모니터링 이벤트 중 하나를 구독할 수 있습니다:
이벤트 이름 | 설명 |
---|---|
| 연결 풀이 생성될 때 생성됩니다. |
| 연결 풀이 준비되면 생성됩니다. |
| 서버 인스턴스가 파괴되기 전 연결 풀이 닫힐 때 생성됩니다. |
| 연결이 생성될 때 생성되지만 작업에 사용될 때 반드시 생성되지는 않습니다. |
| 연결이 성공적으로 핸드셰이크를 완료하고 작업에 사용할 준비가 된 후에 생성됩니다. |
| 연결이 닫힐 때 생성됩니다. |
| 작업이 실행을 위해 연결을 획득하려고 시도할 때 생성됩니다. |
| 작업이 실행을 위한 연결을 획득하지 못할 때 생성됩니다. |
| 작업이 실행을 위한 연결을 성공적으로 획득할 때 생성됩니다. |
| 작업이 실행된 후 연결이 풀에 다시 체크인될 때 생성됩니다. |
| 모든 연결이 닫히고 연결 풀 지워질 때 생성됩니다. |
이벤트 문서 예시
다음 섹션에서는 각 유형의 연결 풀 모니터링 이벤트에 대한 샘플 출력을 보여줍니다.
connectionPoolCreated
ConnectionPoolCreatedEvent { time: 2023-02-13T15:54:06.944Z, address: '...', options: {...} }
connectionPoolReady
ConnectionPoolReadyEvent { time: 2023-02-13T15:56:38.440Z, address: '...' }
connectionPoolClosed
ConnectionPoolClosedEvent { time: 2023-02-13T15:56:38.440Z, address: '...' }
connectionCreated 이벤트
ConnectionCreatedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', connectionId: 1 }
connectionReady
ConnectionReadyEvent { time: 2023-02-13T15:56:38.291Z, address: '...', connectionId: 1, durationMS: 60 }
연결종료
ConnectionClosedEvent { time: 2023-02-13T15:56:38.439Z, address: '...', connectionId: 1, reason: 'poolClosed', serviceId: undefined }
connectionCheckOutStarted 이벤트
ConnectionCheckOutStartedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', }
connectionCheckOutFailed
ConnectionCheckOutFailedEvent { time: 2023-02-13T15:56:38.291Z, address: '...', reason: ..., durationMS: 60 }
connectionCheckedOut
ConnectionCheckedOutEvent { time: 2023-02-13T15:54:07.188Z, address: '...', connectionId: 1, durationMS: 60 }
connectionCheckedIn
ConnectionCheckedInEvent { time: 2023-02-13T15:54:07.189Z, address: '...', connectionId: 1 }
connectionPoolCleared
ConnectionPoolClearedEvent { time: 2023-02-13T15:56:38.439Z, address: '...', serviceId: undefined, interruptInUseConnections: true, }
API 문서
이 가이드 에 설명된 옵션 또는 유형에 대해 자세히 학습 다음 API 문서를 참조하세요.