Docs Menu
Docs Home
/ / /
Node.js 드라이버
/

애플리케이션 이벤트 모니터링

이 가이드 에서는 MongoDB Node.js 운전자 에서 모니터링 설정하다 하고 구성하는 방법을 학습 수 있습니다.

모니터링에는 애플리케이션 성능 관리 라이브러리와 함께 사용할 수 있는 실행 프로그램의 활동에 대한 정보를 수집하는 작업이 포함됩니다.

Node.js 운전자 모니터링하면 드라이버의 리소스 사용량 및 성능을 이해하고 애플리케이션 설계하고 디버깅할 때 정보에 입각한 결정을 내리는 데 도움이 될 수 있습니다.

이 가이드에서는 이와 같은 작업을 수행하는 방법애 대해 학습합니다.

  • 명령 이벤트 모니터링

  • 서버 검색 및 모니터링(SDAM) 이벤트 모니터링

  • 연결 풀 이벤트 모니터링

이 가이드 코드에서 운전자 의 활동에 대한 정보를 사용하는 방법을 보여줍니다. 운전자 에서 이벤트를 기록 방법을 학습 Node.js 드라이버의 로깅 가이드 참조하세요.

애플리케이션 에서 이벤트를 구독 Node.js 운전자 사용하여 이벤트를 모니터 할 수 있습니다.

이벤트 작동 중에 운전자 내에서 발생하는 모든 조치 입니다. Node.js 운전자 이러한 이벤트의 하위 집합을 수신하는 기능이 포함되어 있습니다.

Node.js 운전자 정의된 이벤트를 다음 카테고리로 구성합니다.

  • 명령 이벤트

  • 서버 검색 및 모니터링(SDAM) 이벤트

  • 연결 풀 이벤트

다음 섹션에서는 각 이벤트 카테고리를 모니터링하는 방법에 대해 설명합니다.

명령 이벤트 는 MongoDB database 명령과 관련된 이벤트 입니다. 애플리케이션 에서 운전자 를 구독 하여 하나 이상의 명령 모니터링 이벤트에 액세스 할 수 있습니다.

MongoDB database 명령에 대해 자세히 학습 서버 매뉴얼의 데이터베이스 명령 가이드 참조하세요.

참고

명령 모니터링은 기본적으로 비활성화되어 있습니다. 명령 모니터링을 사용하려면 monitorCommands 옵션을 trueMongoClient 생성자에 전달합니다.

다음 예시에서는 복제본 세트에 연결하고 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

명령이 시작될 때 생성됩니다.

commandSucceeded

명령이 성공할 때 생성됩니다.

commandFailed

명령이 실패할 때 생성됩니다.

CommandStartedEvent {
requestId: 1534,
databaseName: "app",
commandName: "find",
address: 'localhost:27017',
connectionId: 812613,
command: {
find: { firstName: "Jane", lastName: "Doe" }
}
}
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 이벤트 중 하나를 구독할 수 있습니다.

이벤트 이름
설명

serverOpening

인스턴스에 대한 연결이 열릴 때 생성됩니다.

serverClosed

인스턴스에 대한 연결이 닫힐 때 생성됩니다.

serverDescriptionChanged

인스턴스 상태가 변경될 때 생성됩니다(예: 세컨더리에서 프라이머리로).

topologyOpening

인스턴스에 연결을 시도하기 전에 생성됩니다.

topologyClosed

토폴로지의 모든 인스턴스 연결이 닫힌 후에 생성됩니다.

topologyDescriptionChanged

새 프라이머리 투표 또는 mongos 프록시 연결이 끊어지는 등 토폴로지가 변경될 때 생성됩니다.

serverHeartbeatStarted

MongoDB 인스턴스에 hello 명령을 실행하기 전에 생성됩니다.

serverHeartbeatSucceeded

hello 명령이 MongoDB 인스턴스에서 성공적으로 반환될 때 생성됩니다.

serverHeartbeatFailed

특정 MongoDB 인스턴스에 대해 실행된 hello 명령이 성공적인 응답을 반환하지 못할 때 생성됩니다.

다음 섹션에서는 각 유형의 SDAM 이벤트에 대한 샘플 출력을 보여줍니다.

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 필드에는 다음 가능한 값 중 하나가 포함됩니다.

유형
설명

Unknown

알 수 없는 인스턴스

Standalone

독립형 인스턴스

Mongos

Mongo 프록시 인스턴스

PossiblePrimary

하나 이상의 서버가 이를 프라이머리 서버로 인식하지만, 아직 모든 인스턴스에서 확인되지는 않았습니다.

RSPrimary

프라이머리 인스턴스

RSSecondary

세컨더리 인스턴스

RSArbiter

중재자 인스턴스

RSOther

RSGhost

ServerHeartbeatStartedEvent {
connectionId: 'localhost:27017'
}
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 {
duration: 20,
failure: MongoError('some error'),
connectionId: 'localhost:27017'
}
ServerOpeningEvent {
topologyId: 0,
address: 'localhost:27017'
}
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 필드에는 다음 가능한 값 중 하나가 포함됩니다.

유형
설명

Single

독립형 인스턴스

ReplicaSetWithPrimary

프라이머리가 있는 복제본 세트

ReplicaSetNoPrimary

프라이머리가 없는 복제본 세트

Sharded

샤딩된 클러스터

Unknown

알 수 없는 토폴로지

연결 풀 운전자 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

연결 풀이 생성될 때 생성됩니다.

connectionPoolReady

연결 풀이 준비되면 생성됩니다.

connectionPoolClosed

서버 인스턴스가 파괴되기 전 연결 풀이 닫힐 때 생성됩니다.

connectionCreated

연결이 생성될 때 생성되지만 작업에 사용될 때 반드시 생성되지는 않습니다.

connectionReady

연결이 성공적으로 핸드셰이크를 완료하고 작업에 사용할 준비가 된 후에 생성됩니다.

connectionClosed

연결이 닫힐 때 생성됩니다.

connectionCheckOutStarted

작업이 실행을 위해 연결을 획득하려고 시도할 때 생성됩니다.

connectionCheckOutFailed

작업이 실행을 위한 연결을 획득하지 못할 때 생성됩니다.

connectionCheckedOut

작업이 실행을 위한 연결을 성공적으로 획득할 때 생성됩니다.

connectionCheckedIn

작업이 실행된 후 연결이 풀에 다시 체크인될 때 생성됩니다.

connectionPoolCleared

모든 연결이 닫히고 연결 풀 지워질 때 생성됩니다.

다음 섹션에서는 각 유형의 연결 풀 모니터링 이벤트에 대한 샘플 출력을 보여줍니다.

ConnectionPoolCreatedEvent {
time: 2023-02-13T15:54:06.944Z,
address: '...',
options: {...}
}
ConnectionPoolReadyEvent {
time: 2023-02-13T15:56:38.440Z,
address: '...'
}
ConnectionPoolClosedEvent {
time: 2023-02-13T15:56:38.440Z,
address: '...'
}
ConnectionCreatedEvent {
time: 2023-02-13T15:56:38.291Z,
address: '...',
connectionId: 1
}
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
}
ConnectionCheckOutStartedEvent {
time: 2023-02-13T15:56:38.291Z,
address: '...',
}
ConnectionCheckOutFailedEvent {
time: 2023-02-13T15:56:38.291Z,
address: '...',
reason: ...,
durationMS: 60
}
ConnectionCheckedOutEvent {
time: 2023-02-13T15:54:07.188Z,
address: '...',
connectionId: 1,
durationMS: 60
}
ConnectionCheckedInEvent {
time: 2023-02-13T15:54:07.189Z,
address: '...',
connectionId: 1
}
ConnectionPoolClearedEvent {
time: 2023-02-13T15:56:38.439Z,
address: '...',
serviceId: undefined,
interruptInUseConnections: true,
}

이 가이드 에 설명된 옵션 또는 유형에 대해 자세히 학습 다음 API 문서를 참조하세요.

돌아가기

모니터링 및 로깅

이 페이지의 내용