Command Monitoring命令监视
On this page本页内容
Overview概述
This guide shows you how to monitor the success or failure of commands sent by the driver to your MongoDB deployment.本指南向您展示如何监控驱动程序向MongoDB部署发送的命令的成功或失败。
Read this guide if you need to record command status in your application or want to explore the information provided in these events.如果您需要在应用程序中记录命令状态,或者想了解这些事件中提供的信息,请阅读本指南。
Event Subscription Example事件订阅示例
You can access one or more command monitoring 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 command 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, { monitorCommands:true });
//Replace <event name> with the name of the event you are subscribing to.将<event name>替换为您正在订阅的事件的名称。
const eventName = "<event name>";
client.on(eventName, event => {
console.log(`received ${eventName}: ${JSON.stringify(event, null, 2)}`);
});
async function run() {
try {
//Establish and verify connection建立并验证连接
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully");
} finally {
//Ensures that the client will close when you finish/error确保客户端在您完成/出错时关闭
await client.close();
}
}
run().catch(console.dir);
Command monitoring is disabled by default. 默认情况下,命令监视处于禁用状态。To enable command monitoring, pass the 要启用命令监视,请将monitorCommands
option as true
to your MongoClient
constructor.monitorCommand
选项作为true
传递给MongoClient
构造函数。
Event Descriptions事件描述
You can subscribe to any of the following command monitoring events:您可以订阅以下任何命令监视事件:
commandStarted | |
commandSucceeded | |
commandFailed |
Example Event Documents事件文档示例
The following sections show sample output for each type of command monitoring event.以下部分显示了每种类型的命令监视事件的示例输出。
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: 1586380205,
reply: {
cursor: {
firstBatch: [
{
_id: ObjectId("5e8e2ca217b5324fa9847435"),
firstName: "Jane",
lastName: "Doe"
}
],
_id: 0,
ns: "app.users"
},
ok: 1,
operationTime: 1586380205
}
}
commandFailed
CommandFailedEvent {
requestId: 1534,
commandName: "find",
address: 'localhost:27017',
connectionId: 812613,
failure: Error("something failed"),
duration: 1586380205
}