ANNOUNCEMENT: Voyage AI joins MongoDB to power more accurate and trustworthy AI applications on Atlas.
Learn more
Docs 菜单

监控

In this guide, you can learn how to set up and configure 监控 in the Kotlin Sync driver.

Monitoring is the process of getting information about the activities a running program performs for use in an application or an application performance management library.

You can use the Kotlin Sync driver to monitor cluster, driver command, and connection pool events. These features help you make informed decisions when designing and debugging your application.

This guide shows how to perform the following tasks:

提示

This guide shows how to use information about the meta activity of the driver. To learn how to record data transactions, see the Monitoring Data Changes page.

如需监控事件,必须在 MongoClient 实例上注册监听器

事件是运行程序时发生的任何操作。驱动程序包括监听驱动程序运行时发生的事件子集的功能。

监听器是在某些事件发生时执行某些操作的类。监听器的 API 定义了其可以响应的事件。

Each method of a listener class represents a response to a certain event, and accepts as an argument an event object representing the event.

The Kotlin Sync driver organizes the events it defines into three categories:

  • 命令事件

  • Server Discovery and Monitoring events

  • 连接池事件

The following sections show how to monitor each event category. For a full list of the events you can monitor, see the Java event package.

命令事件是与 MongoDB 数据库命令相关的事件。生成命令事件的数据库命令的一些示例包括 findinsertdeletecount

要监控命令事件,请创建一个实现CommandListener接口的类,并使用MongoClient实例。

For more information on MongoDB database commands, see the MongoDB manual entry on database commands in the MongoDB Server manual.

注意

内部命令

The driver does not publish events for commands it calls internally. This includes database commands the driver uses to monitor your cluster and commands related to connection establishment, such as the initial hello command.

重要

编辑输出

作为安全措施,驱动程序会编辑某些命令事件的内容。 这可以保护这些命令事件中包含的敏感信息。 有关已编辑命令事件的完整列表,请参阅 MongoDB 命令日志记录和监控规范。

This example shows how to make a counter for database commands. The counter keeps track of the number of times the driver successfully executes each database command and prints this information every time a database command finishes.

To make a counter, follow these steps:

  1. 创建具有计数器功能的类,实现 CommandListener 接口。

  2. Add an instance of the new class to a MongoClientSettings object.

  3. Configure your MongoClient instance with the MongoClientSettings object.

The following code implements these steps:

import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import com.mongodb.event.*
import com.mongodb.MongoClientSettings
import com.mongodb.ConnectionString
class CommandCounter : CommandListener {
private val commands = mutableMapOf<String, Int>()
override fun commandSucceeded(event: CommandSucceededEvent) {
val commandName = event.commandName
val count = commands[commandName] ?: 0
commands[commandName] = count + 1
println(commands.toString())
}
override fun commandFailed(event: CommandFailedEvent) {
println("Failed execution of command '${event.commandName}' with id ${event.requestId}")
}
}
fun main() {
val uri = "<connection string uri>"
// Instantiate your new listener
val commandCounter = CommandCounter()
// Include the listener in your client settings
val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.addCommandListener(commandCounter)
.build()
// Connect to your database
val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
// Run some commands to test the counter
collection.find().firstOrNull()
collection.find().firstOrNull()
mongoClient.close()
}
{find=1}
{find=2}
{find=2, endSessions=1}

For more information on the classes and methods mentioned in this section, see the following API documentation:

服务器发现与监控 (SDAM) 事件是指与驱动程序连接到的 MongoDB 实例或集群的状态变化相关的事件。

The driver defines nine SDAM events and provides the following listener interfaces, which listen for three SDAM events each:

To monitor a type of SDAM event, create a class that implements one of the three preceding interfaces and register an instance of that class with your MongoClient instance.

For a detailed description of each SDAM event, see the MongoDB SDAM monitoring events specification.

This example shows how to make a listener class that prints a message about the write availability of your MongoDB instance.

To make an event that reports write status, perform the following tasks:

  1. Make a class that tracks cluster description changes, and implements the ClusterListener interface.

  2. Add an instance of the new class to a MongoClientSettings object.

  3. Configure your MongoClient instance with the MongoClientSettings object.

The following code implements these steps:

import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import com.mongodb.event.*
import com.mongodb.MongoClientSettings
import com.mongodb.ConnectionString
class IsWriteable : ClusterListener {
private var isWritable = false
override fun clusterDescriptionChanged(event: ClusterDescriptionChangedEvent) {
if (!isWritable) {
if (event.newDescription.hasWritableServer()) {
isWritable = true
println("Able to write to cluster")
}
} else {
if (!event.newDescription.hasWritableServer()) {
isWritable = false
println("Unable to write to cluster")
}
}
}
}
fun main() {
val uri = "<connection string uri>"
// Instantiate your new listener
val clusterListener = IsWriteable()
// Include the listener in your client settings
val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.applyToClusterSettings { builder ->
builder.addClusterListener(clusterListener)
}
.build()
// Connect to your database
val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
// Run a command to trigger a ClusterDescriptionChangedEvent event
collection.find().firstOrNull()
mongoClient.close()
}
Able to write to server

For more information on the classes and methods mentioned in this section, see the following API documentation:

A connection pool event is an event related to a connection pool held by the driver. 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 performs with a MongoDB instance and can help your application run faster.

To monitor connection pool events, create a class that implements the ConnectionPoolListener interface and register an instance of that class with your MongoClient instance.

This example shows how to make a listener class that prints a message each time you check out a connection from your connection pool.

To make an event that reports connection checkouts, perform the following tasks:

  1. Make a class that tracks checkouts and implements the CommandListener interface.

  2. Add an instance of the new class to a MongoClientSettings object.

  3. Configure your MongoClient instance with the MongoClientSettings object.

The following code implements these steps:

import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import com.mongodb.event.*
import com.mongodb.MongoClientSettings
import com.mongodb.ConnectionString
class ConnectionPoolLibrarian : ConnectionPoolListener {
override fun connectionCheckedOut(event: ConnectionCheckedOutEvent) {
println("Let me get you the connection with id ${event.connectionId.localValue}...")
}
override fun connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent) {
println("Something went wrong! Failed to checkout connection.")
}
}
fun main() {
val uri = "<connection string uri>"
// Instantiate your new listener
val cpListener = ConnectionPoolLibrarian()
// Include the listener in your client settings
val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.applyToConnectionPoolSettings({
it.addConnectionPoolListener(cpListener)
})
.build()
// Connect to your database
val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
// Run some commands to test the counter
collection.find().firstOrNull()
mongoClient.close()
}
Let me get you the connection with id 21...

For more information on the classes and methods mentioned in this section, see the following API documentation:

您可以使用“Java 管理扩展”(JMX) 监控连接池事件。JMX 提供了监控应用程序和设备的工具。

For more information on JMX, see the official Oracle JMX documentation.

要启用 JMX 连接池监控,请将 JMXConnectionPoolListener 类的实例添加到 MongoClient 对象。

JMXConnectionPoolListener 类执行以下操作:

  1. Creates MXBean instances for each mongod or mongos process the driver maintains a connection pool with.

  2. Registers these MXBean instances with the platform MBean server.

在平台 MBean 服务器上注册的 MXBean 具有以下属性:

属性
说明

clusterId

客户端生成的唯一标识符。当应用程序有多个 MongoClient 实例连接到同一 MongoDB 部署时,该标识符可确保驱动程序生成的每个 MXBean 都有唯一的名称。

host

运行 mongodmongos 进程的计算机的主机名。

port

mongodmongos 进程正在侦听的端口。

minSize

连接池的最小大小,包括空闲和正在使用的连接。

maxSize

连接池的最大大小,包括空闲连接和使用中的连接。

size

连接池的当前大小,包括空闲连接和使用中的连接。

checkedOutCount

当前正在使用的连接数。

此驱动程序创建的所有 MXBean 实例均位于 "org.mongodb.driver" 域中。

For more information on the topics discussed in this subsection, see the following resources from Oracle:

This example shows how you can monitor the driver's connection pools using JMX and JConsole. JConsole is a JMX compliant GUI monitoring tool that comes with the Java Platform.

提示

查阅官方 JMX 与 JConsole 文档

此示例中对 JMX 和 JConsole 的描述只是说明性的,而不是事实来源。 有关保证的最新信息,请查阅以下Oracle官方资源:

以下代码段将 JMXConnectionPoolListener 添加到 MongoClient 实例。然后代码暂停执行,以便您可以导航到 JConsole 并检查连接池。

import com.mongodb.kotlin.client.MongoClient
import org.bson.Document
import com.mongodb.MongoClientSettings
import com.mongodb.ConnectionString
import com.mongodb.management.JMXConnectionPoolListener
fun main() {
val uri = "<connection string uri>"
// Instantiate your JMX listener
val connectionPoolListener = JMXConnectionPoolListener()
// Include the listener in your client settings
val settings = MongoClientSettings.builder()
.applyConnectionString(ConnectionString(uri))
.applyToConnectionPoolSettings {
it.addConnectionPoolListener(connectionPoolListener)
}
.build()
try {
// Connect to your database
val mongoClient = MongoClient.create(settings)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
collection.find().firstOrNull()
collection.find().firstOrNull()
println("Navigate to JConsole to see your connection pools...")
// Pause execution
Thread.sleep(Long.MAX_VALUE)
mongoClient.close()
} catch (e: Exception) {
e.printStackTrace()
}
}
Navigate to JConsole to see your connection pools...

Once you have started your server, open JConsole in your terminal by using the following command:

jconsole

打开 JConsole 后,在图形界面中执行以下操作:

  1. Select the process running the preceding example code.

  2. Press Insecure Connection in the warning dialog box.

  3. 单击 MBeans 标签页。

  4. 检查 "org.mongodb.driver" 域下的连接池事件。

When you no longer want to inspect your connection pools in JConsole, do the following:

  1. 关闭 JConsole窗口以退出 JConsole。

  2. Stop the program running by the preceding code snippet.

For more information on JMX and JConsole, see the following resources from Oracle:

For more information on the JMXConnectionPoolListener class, see the API documentation for JMXConnectionPoolListener.

如果使用分布式跟踪系统,则可以包含驱动程序的事件数据。分布式跟踪系统是种应用程序,可在请求传播到面向服务架构中的不同服务时对其进行跟踪。

If you use the driver in a Spring Cloud application, use Spring Cloud Sleuth to include MongoDB event data in the Zipkin distributed tracing system.

If you do not use Spring Cloud or want to include driver event data in a distributed tracing system other than Zipkin, you must write a command event listener that manages spans for your desired distributed tracing system.

提示

To learn more about the concepts discussed in this section, review the following resources: