Overview概述
In this guide, you can learn how to set up and configure monitoring in the MongoDB Node.js driver.在本指南中,您可以学习如何在MongoDB Node.js驱动程序中设置和配置监控。
Monitoring involves collecting information about the activities of a running program, which you can use with an application performance management library.监控涉及集合有关正在运行的程序活动的信息,您可以将其与应用程序性能管理库一起使用。
Monitoring the Node.js driver lets you understand the driver's resource usage and performance, and can help you make informed decisions when designing and debugging your application.监控Node.js驱动程序可以让您了解驱动程序的资源使用情况和性能,并可以帮助您在设计和调试应用程序时做出明智的决定。
In this guide you will learn how to perform these tasks:在本指南中,您将学习如何执行这些任务:
Monitor Command Events监视命令事件Monitor Server Discovery and Monitoring (SDAM) Events监视服务器发现和监视(SDAM)事件Monitor Connection Pool Events监视连接池事件
This guide shows how to use information about the activity of the driver in code. To learn how to record events in the driver, see the Node.js driver's Logging guide.本指南展示了如何在代码中使用有关驱动程序活动的信息。要了解如何在驱动程序中记录事件,请参阅Node.js驱动程序的日志指南。
Monitor Events监控事件
You can monitor events using the Node.js driver by subscribing to them in your application.您可以通过在应用程序中订阅Node.js驱动程序来监视事件。
An event is any action that occurs within the driver during its operation. The Node.js driver includes functionality for listening to a subset of these events.事件是指驾驶员在操作过程中发生的任何动作。Node.js驱动程序包括监听这些事件子集的功能。
The Node.js driver organizes the events it defines into the following categories:Node.js驱动程序将它定义的事件组织成以下类别:
Command Events命令事件Server Discovery and Monitoring (SDAM) Events服务器发现和监视(SDAM)事件Connection Pool Events连接池事件
The following sections show how to monitor each event category.以下部分显示了如何监视每个事件类别。
Command Events命令事件
A command event is an event related to a MongoDB database command. You can access one or more command monitoring events using the driver by subscribing to them in your application.命令事件是与MongoDB数据库命令相关的事件。您可以通过在应用程序中订阅驱动程序来访问一个或多个命令监视事件。
To learn more about MongoDB database commands, see the Database Commands guide in the Server Manual.要了解有关MongoDB数据库命令的更多信息,请参阅服务器手册中的数据库命令指南。
Note
Command monitoring is disabled by default. To enable command monitoring, pass the 默认情况下,命令监视处于禁用状态。要启用命令监视,请将monitorCommands option as true to your MongoClient constructor.monitorCommands选项作为true传递给MongoClient构造函数。
Example示例
The following example demonstrates connecting to a replica set and subscribing to one of the command monitoring events created by the MongoDB deployment:以下示例演示了连接到副本集并订阅MongoDB部署创建的命令监视事件之一:
/* Subscribe to an event订阅活动 */
const { MongoClient } = require("mongodb");
// Replace the following with your MongoDB deployment's connection string将以下内容替换为MongoDB部署的连接字符串
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将<event name>替换为您订阅的事件的名称
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建立并验证与“admin”数据库的连接
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);Event Descriptions事件描述
You can subscribe to any of the following command monitoring events:您可以订阅以下任何命令监视事件:
commandStarted | |
commandSucceeded | |
commandFailed |
The following sections show sample output for each of the preceding commands. Your output might differ depending on the command you run and the options you set.以下部分显示了前面每个命令的示例输出。输出可能因运行的命令和设置的选项而异。
commandStarted
CommandStartedEvent {
name: 'commandStarted',
address: 'localhost:27017',
connectionId: 812613,
serviceId: undefined,
requestId: 1534,
databaseName: 'app',
commandName: 'find',
command: {
find: { firstName: "Jane", lastName: "Doe" }
},
serverConnectionId: 27177n
}commandSucceeded
CommandSucceededEvent {
name: 'commandSucceeded',
address: 'localhost:27017',
connectionId: 812613,
serviceId: undefined,
requestId: 1534,
commandName: 'find',
duration: 15,
reply: {
cursor: {
firstBatch: [
{
_id: ObjectId("5e8e2ca217b5324fa9847435"),
firstName: "Jane",
lastName: "Doe"
}
],
_id: 0,
ns: "app.users"
},
ok: 1,
operationTime: 1586380205
},
serverConnectionId: 27096n,
databaseName: 'app'
}commandFailed
CommandFailedEvent {
name: 'commandFailed',
address: 'localhost:27017',
connectionId: 812613,
serviceId: undefined,
requestId: 1534,
commandName: 'find',
duration: 11,
failure: Error("something failed"),
serverConnectionId: 27208n,
databaseName: 'app'
}Server Discovery and Monitoring Events服务器发现和监视事件
The Node.js driver creates topology events, also known as SDAM events, when there is a change in the state of the instance or cluster that you connected to. For example, the driver creates an event when you establish a new connection or if the cluster elects a new primary node.当您连接的实例或集群的状态发生变化时,Node.js驱动程序会创建拓扑事件,也称为SDAM事件。例如,当您建立新连接或集群选择新的主节点时,驱动程序会生成一个事件。
To learn more about topology events, see the Replication guide in the Server Manual.要了解有关拓扑事件的更多信息,请参阅服务器手册中的复制指南。
The following sections demonstrate how to record topology changes in your application and explore the information provided in these events.以下部分将演示如何记录应用程序中的拓扑更改,并探索这些事件中提供的信息。
Event Subscription Example事件订阅示例
You can access one or more SDAM events by subscribing to them in your application. The following example demonstrates connecting to a replica set and subscribing to one of the SDAM events created by the MongoDB deployment:您可以通过在应用程序中订阅一个或多个SDAM事件来访问它们。以下示例演示了连接到副本集并订阅MongoDB部署创建的SDAM事件之一:
/* Subscribe to SDAM event订阅SDAM活动 */
const { MongoClient } = require("mongodb");
// Replace the following with your MongoDB deployment's connection string将以下内容替换为MongoDB部署的连接字符串
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将<event name>替换为您订阅的事件的名称
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);Event Descriptions事件描述
You can subscribe to any of the following SDAM events:您可以订阅以下任何SDAM事件:
serverOpening | |
serverClosed | |
serverDescriptionChanged | |
topologyOpening | |
topologyClosed | |
topologyDescriptionChanged | mongos代理连接。 |
serverHeartbeatStarted | hello command to a MongoDB instance.hello命令之前创建。 |
serverHeartbeatSucceeded | hello command returns successfully from a MongoDB instance.hello命令从MongoDB实例成功返回时创建。 |
serverHeartbeatFailed | hello command issued to a specific MongoDB instance fails to return a successful response.hello命令未能返回成功响应时创建。 |
Example Event Documents事件文档示例
The following sections show sample output for each type of SDAM event.以下部分显示了每种类型的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
}
}
The 此事件中type field of the ServerDescription object in this event contains one of the following possible values:ServerDescription对象的type字段包含以下可能值之一:
Unknown | |
Standalone | |
Mongos | |
PossiblePrimary | |
RSPrimary | |
RSSecondary | |
RSArbiter | |
RSOther | |
RSGhost |
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'
}topologyOpening
TopologyOpeningEvent {
topologyId: 0
}topologyClosed
TopologyClosedEvent {
topologyId: 0
}topologyDescriptionChanged
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
}
}
The 此事件中type field of the TopologyDescription object in this event contains one of the following possible values:TopologyDescription对象的type字段包含以下可能值之一:
Single | |
ReplicaSetWithPrimary | |
ReplicaSetNoPrimary | |
Sharded | |
Unknown |
Connection Pool Events连接池事件
A connection pool is a set of open TCP connections your driver maintains with a MongoDB instance. Connection pools help reduce the number of network handshakes your application needs to perform and can help your application run faster.连接池是驱动程序与MongoDB实例维护的一组开放TCP连接。连接池有助于减少应用程序需要执行的网络握手次数,并可以帮助应用程序运行得更快。
The following sections demonstrate how to record connection pool events in your application and explore the information provided in these events.以下部分将演示如何在应用程序中记录连接池事件,并探索这些事件中提供的信息。
Event Subscription Examples事件订阅示例
You can access one or more connection pool events using the driver by subscribing to them in your application. The following example demonstrates connecting to a replica set and subscribing to one of the connection pool monitoring events created by the MongoDB deployment:您可以通过在应用程序中订阅驱动程序来访问一个或多个连接池事件。以下示例演示了连接到副本集并订阅MongoDB部署创建的连接池监控事件之一:
const { MongoClient } = require("mongodb");
// Replace the following with your MongoDB deployment's connection string将以下内容替换为MongoDB部署的连接字符串
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将<event name>替换为您订阅的事件的名称
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);
Connection pool monitoring events can aid you in debugging and understanding the behavior of your application's connection pool. The following example uses connection pool monitoring events to return a count of checked-out connections in the pool:连接池监视事件可以帮助您调试和理解应用程序连接池的行为。以下示例使用连接池监视事件返回池中已签出连接的计数:
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当触发connectionCheckedIn事件时,减少从池中检出的连接数
client.on('connectionCheckedIn', onCheckin);
// Increases count of connections checked out of the pool when connectionCheckedOut event is triggered当触发connectionCheckedOut事件时,增加从池中检出的连接数
client.on('connectionCheckedOut', onCheckout);
// Cleans up event listeners when client is closed关闭客户端时清理事件侦听器
client.on('close', onClose);
return {
count: () => checkedOut,
cleanUp: onClose
};
}Event Descriptions事件描述
You can subscribe to any of the following connection pool monitoring events:您可以订阅以下任何连接池监视事件:
connectionPoolCreated | |
connectionPoolReady | |
connectionPoolClosed | |
connectionCreated | |
connectionReady | |
connectionClosed | |
connectionCheckOutStarted | |
connectionCheckOutFailed | |
connectionCheckedOut | |
connectionCheckedIn | |
connectionPoolCleared |
Example Event Documents事件文档示例
The following sections show sample output for each type of connection pool monitoring event.以下部分显示了每种类型的连接池监视事件的示例输出。
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
}connectionClosed
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 Documentation文档
To learn more about any of the options or types discussed in this guide, see the following API documentation:要了解有关本指南中讨论的任何选项或类型的更多信息,请参阅以下API文档: