Docs Home / Node.js Driver

Monitor Application Events监视应用程序事件

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:在本指南中,您将学习如何执行这些任务:

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:您可以订阅以下任何命令监视事件:

Event Name事件名称Description描述
commandStartedCreated when a command is started.命令启动时创建。
commandSucceededCreated when a command succeeded.命令成功时创建。
commandFailedCreated when a command failed.命令失败时创建。

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事件:

Event Name事件名称Description描述
serverOpeningCreated when a connection to an instance opens.当与实例的连接打开时创建。
serverClosedCreated when a connection to an instance closes.当与实例的连接关闭时创建。
serverDescriptionChangedCreated when an instance state changes (such as from secondary to primary).当实例状态更改时创建(例如从辅助状态更改为主状态)。
topologyOpeningCreated before attempting a connection to an instance.在尝试连接到实例之前创建。
topologyClosedCreated after all instance connections in the topology close.在拓扑中的所有实例连接关闭后创建。
topologyDescriptionChangedCreated when the topology changes, such as an election of a new primary or a mongos proxy disconnecting.当拓扑结构发生变化时创建,例如选举新的主代理或断开mongos代理连接。
serverHeartbeatStartedCreated before issuing a hello command to a MongoDB instance.在向MongoDB实例发出hello命令之前创建。
serverHeartbeatSucceededCreated when the hello command returns successfully from a MongoDB instance.hello命令从MongoDB实例成功返回时创建。
serverHeartbeatFailedCreated when a hello command issued to a specific MongoDB instance fails to return a successful response.当向特定MongoDB实例发出的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字段包含以下可能值之一:

Type类型Description描述
UnknownUnknown instance未知实例
StandaloneStandalone instance独立实例
MongosMongos proxy instanceMongos代理实例
PossiblePrimaryAt least one server recognizes this as the primary, but is not yet verified by all instances.至少有一个服务器将其识别为主服务器,但尚未被所有实例验证。
RSPrimaryPrimary instance主实例
RSSecondarySecondary instance次要实例
RSArbiterArbiter instance仲裁员实例
RSOtherSee the RSGhost and RSOther specification for more details有关更多详细信息,请参阅RSGhost和RSOther规范
RSGhostSee the RSGhost and RSOther specification for more details有关更多详细信息,请参阅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'
}
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字段包含以下可能值之一:

Type类型Description描述
SingleStandalone instance独立实例
ReplicaSetWithPrimaryReplica set with a primary带有主副本的副本集
ReplicaSetNoPrimaryReplica set with no primary没有主副本的副本集
ShardedSharded cluster分片集群
UnknownUnknown topology未知拓扑

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:您可以订阅以下任何连接池监视事件:

Event Name活动名称Description描述
connectionPoolCreatedCreated when a connection pool is created.创建连接池时创建。
connectionPoolReadyCreated when a connection pool is ready.连接池就绪时创建。
connectionPoolClosedCreated when a connection pool is closed before server instance destruction.在服务器实例销毁之前关闭连接池时创建。
connectionCreatedCreated when a connection is created, but not necessarily when it is used for an operation.在创建连接时创建,但不一定是在用于操作时创建。
connectionReadyCreated after a connection has successfully completed a handshake and is ready to be used for operations.在连接成功完成握手并准备用于操作后创建。
connectionClosedCreated when a connection is closed.连接关闭时创建。
connectionCheckOutStartedCreated when an operation attempts to acquire a connection for execution.当操作尝试获取连接以供执行时创建。
connectionCheckOutFailedCreated when an operation fails to acquire a connection for execution.当操作无法获取执行连接时创建。
connectionCheckedOutCreated when an operation successfully acquires a connection for execution.当操作成功获取要执行的连接时创建。
connectionCheckedInCreated when a connection is checked back into the pool after an operation is executed.在执行操作后将连接签回池中时创建。
connectionPoolClearedCreated when all connections are closed and the connection pool is cleared.在关闭所有连接并清除连接池时创建。

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文档: