命令监控
概述
本指南向您展示了如何监控驱动程序发送到您的MongoDB部署的命令的成功或失败情况。
以下部分演示了如何在您的应用程序中记录命令状态,并探索这些事件提供的信息。
事件订阅示例
您可以通过在应用程序中订阅这些事件来访问一个或多个命令监控事件。以下示例演示了连接到副本集并订阅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>"; // Subscribe to a specified event and print a message when the event is received client.on(eventName, event => console.log(event)); async function run() { try { // Establish and verify connection to the "admin" database await client.db("admin").command({ ping: 1 }); console.log("Connected successfully"); } finally { // Close the database connection on completion or error await client.close(); } } run().catch(console.dir);
注意
命令监控默认是禁用的。要启用命令监控,请将monitorCommands
选项作为true
传递给您的MongoClient
构造函数。
事件描述
您可以订阅以下任何命令监控事件
事件名称 | 描述 |
---|---|
commandStarted | 当命令启动时创建。 |
commandSucceeded | 当命令成功时创建。 |
commandFailed | 当命令失败时创建。 |
示例事件文档
以下部分显示了每种命令监控事件的示例输出。
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 }