Overview
本指南将介绍如何使用 Java 驱动程序进行 OpenTelemetry 跟踪。 是一个开源的可观测性框架,它提供了一种标准化的方法来检测、生成、收集和导出遥测数据。
The Java driver emits trace data through Micrometer Observation. Register an ObservationRegistry that connects to OpenTelemetry on your MongoClientSettings object. The driver then creates spans that represent your MongoDB operations, such as queries and transactions. The spans include attributes that follow OpenTelemetry semantic conventions.
注意
OpenTelemetry tracing is available in Java driver 5.7 or later. The observability API has Alpha release status and might change in future driver versions.
样本数据
The example on this page uses the sample_mflix.movies collection from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see Get Started with the Java Driver.
Dependencies
该驱动程序不依赖于 Micrometer 或 OpenTelemetry 库。要使用跟踪功能,请将以下依赖项添加到您的应用程序中:
micrometer-tracing-bom:千分尺追踪物料清单 (BOM)。管理兼容版本的千分尺和千分尺追踪依赖项。micrometer-observation: Provides theObservationRegistryand the Micrometer Observation API.micrometer-tracing-bridge-otel将微米观测与 OpenTelemetry 连接起来。micrometer-tracing-integration-test: Provides an in-memory OpenTelemetry exporter. The example on this page uses this exporter so you can inspect the spans the driver produces. In your application, replace this dependency with the exporter for your tracing backend, such as the OTLP (OpenTelemetry Protocol) exporter,opentelemetry-exporter-otlp.
Select from the following Maven and Gradle tabs to view instructions for adding the dependencies:
将以下代码添加到您的 pom.xml 文件中:
<dependencyManagement> <dependencies> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-bom</artifactId> <version>1.5.4</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement>
<dependencies> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-observation</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-bridge-otel</artifactId> </dependency> <dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-tracing-integration-test</artifactId> </dependency></dependencies>将以下代码添加到您的 build.gradle.kts 文件中:
dependencies { implementation(platform("io.micrometer:micrometer-tracing-bom:1.5.4")) implementation("io.micrometer:micrometer-observation") implementation("io.micrometer:micrometer-tracing-bridge-otel") implementation("io.micrometer:micrometer-tracing-integration-test")}Spring Boot
If your application uses Spring Boot, select from the following Maven and Gradle tabs to view the dependencies to add instead:
Add the following code to your pom.xml file. Spring Boot's dependency management pins an older driver version than the one the observability API requires, so set the mongodb.version property to override it:
<properties> <mongodb.version>5.14.0</mongodb.version></properties>
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-opentelemetry</artifactId> </dependency></dependencies>Add the following code to your build.gradle.kts file. Spring Boot's dependency management pins an older driver version than the one the observability API requires, so override the mongodb.version property:
ext["mongodb.version"] = "5.14.0"
dependencies { implementation("org.springframework.boot:spring-boot-starter-data-mongodb") implementation("org.springframework.boot:spring-boot-starter-opentelemetry")}Spring Boot's dependency management supplies compatible versions for these starters, with the Micrometer and Micrometer Tracing versions they depend on. To use this dependency management, inherit from spring-boot-starter-parent or import the spring-boot-dependencies BOM. You don't need the Micrometer Tracing BOM shown earlier in this section.
This section targets Spring Boot 4. If your application uses Spring Boot 3, add the following dependencies instead of spring-boot-starter-opentelemetry:
spring-boot-starter-actuatormicrometer-tracing-bridge-otelopentelemetry-exporter-otlp
启用 OpenTelemetry 跟踪
To enable tracing, create an ObservationRegistry and connect it to your OpenTelemetry SDK and exporter. Then, pass the registry to a MicrometerObservabilitySettings object, and apply the settings to your MongoClientSettings object by using the observabilitySettings() method.
The following example configures the driver to emit tracing spans by using an in-memory OpenTelemetry exporter, then runs a find command to generate mongodb.operation and mongodb.command spans. Replace the in-memory exporter with the exporter for your tracing backend:
String uri = "<connection string URI>";
ObservationRegistry observationRegistry = ObservationRegistry.create();
MicrometerObservabilitySettings micrometerSettings = ObservabilitySettings.micrometerBuilder() .observationRegistry(observationRegistry) .build();
MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)) .observabilitySettings(micrometerSettings) .build();
// Registers an in-memory OpenTelemetry exporter so this example can// inspect the spans the driver emits. In your application, configure// your OpenTelemetry SDK with the exporter for your tracing backend// instead, such as the OTLP exporter.try (InMemoryOtelSetup otelSetup = InMemoryOtelSetup.builder().register(observationRegistry); MongoClient mongoClient = MongoClients.create(settings)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies");
// Runs a find() command to generate "mongodb.operation" and "mongodb.command" spans List<Document> results = collection.find().limit(1).into(new ArrayList<>());}Spring Boot
Spring Boot Actuator already creates an ObservationRegistry bean when Micrometer Observation is on the classpath, and Spring Boot's auto-configuration creates the MongoClient for you. To connect the two, define a MongoClientSettingsBuilderCustomizer bean that applies ObservabilitySettings to the auto-configured MongoClientSettings.Builder:
注意
The following example uses the Spring Boot 4 MongoClientSettingsBuilderCustomizer package. If your application uses Spring Boot 3, import this class from org.springframework.boot.autoconfigure.mongo instead.
import com.mongodb.observability.ObservabilitySettings;import io.micrometer.observation.ObservationRegistry;import org.springframework.boot.mongodb.autoconfigure.MongoClientSettingsBuilderCustomizer;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;
@Configurationpublic class MongoTracingConfig {
@Bean public MongoClientSettingsBuilderCustomizer otelMongoClientSettingsBuilderCustomizer( ObservationRegistry observationRegistry) { return builder -> builder.observabilitySettings( ObservabilitySettings.micrometerBuilder() .observationRegistry(observationRegistry) .build()); }
}请在应用程序属性中配置采样率和 OTLP 导出器端点,而不是构建 OpenTelemetry SDK,如下例所示:
management: tracing: sampling: probability: 1.0 otlp: tracing: endpoint: "http://localhost:4318/v1/traces"了解更多信息,请参阅“追踪”部分。 在 Spring Boot 参考文档中。
配置跟踪选项
To configure tracing, use the following MicrometerObservabilitySettings.Builder methods:
方法 | Argument Type | 说明 |
|---|---|---|
|
| 设置驱动程序用于创建跟踪跨度的注册表。启用跟踪功能需要此设置。 |
|
| When set to 默认: |
|
| Sets the maximum length of the command text captured in the 默认: |
|
| Sets a custom convention to control the tag names and values the driver produces for MongoDB observations. If you don't set a convention, the driver uses |
The following example sets enableCommandPayloadTracing to true and maxQueryTextLength to 1024, which captures up to 1024 characters of the command text:
String uri = "<connection string URI>";
ObservationRegistry observationRegistry = ObservationRegistry.create();
MicrometerObservabilitySettings micrometerSettings = ObservabilitySettings.micrometerBuilder() .observationRegistry(observationRegistry) .enableCommandPayloadTracing(true) .maxQueryTextLength(1024) .build();
MongoClientSettings settings = MongoClientSettings.builder() .applyConnectionString(new ConnectionString(uri)) .observabilitySettings(micrometerSettings) .build();您还可以在驱动程序级别配置以下环境变量:
OBSERVABILITY_MONGODB_ENABLED: Enables or disables tracing for everyMongoClientinstance that has anObservationRegistryconfigured.OBSERVABILITY_MONGODB_QUERY_TEXT_MAX_LENGTH: Sets the maximum length of the command text captured in thedb.query.textattribute.
操作跟踪
Java驱动程序创建以下类型的span:
跨度类型 | 说明 |
|---|---|
| Created for each user-initiated operation, such as |
| 为驱动程序发送到服务器的每个网络协议命令创建。命令跨度嵌套在其对应的操作跨度下。 |
| 事务在启动时创建,在事务提交或中止时结束。 |
例如,查找操作会创建一个操作级跨度,其中包含一个嵌套的命令级跨度,如下层次结构所示:
find sample_mflix.movies └── findSpan 属性
Java 驱动程序遵循 OpenTelemetry 语义约定,并包含提供有关每个操作的上下文的属性。
常规属性
Span 包含以下通用属性:
db.system.name:始终设立为mongodbdb.operation.name: 高级操作的名称(仅限操作跨度)db.operation.summary: 高级操作摘要(仅限操作 span)db.command.name:MongoDB 命令的名称(仅限命令 span)db.namespace:数据库名称db.collection.name: 集合名称(如果适用)db.query.summary:查询摘要(仅限命令 span)
网络和连接属性
命令跨度包含以下属性:
server.address: MongoDB 服务器托管server.port: MongoDB服务器端口network.transport传输协议,例如tcpdb.mongodb.server_connection_id:服务器分配的连接IDdb.mongodb.driver_connection_id:驱动程序分配的连接ID
会话、事务和游标属性
在适用情况下,命令跨度包含以下属性:
db.mongodb.lsid逻辑会话 IDdb.mongodb.txn_number交易编号db.mongodb.cursor_id:游标 ID,用于返回游标的操作
查询属性
When you set enableCommandPayloadTracing to true, command spans include the following attribute:
db.query.text命令文本,已截断为配置值。maxQueryTextLength
错误属性
当操作失败时,驱动程序会将异常详细信息记录为以下属性:
exception.type: 异常类型exception.message: 异常消息exception.stacktrace: 异常堆栈跟踪db.response.status_code: MongoDB 错误代码(仅限命令 span)
安全和日志校订
驱动程序应用以下安全措施来保护敏感信息:
驱动程序不会为以下命令创建命令跨度:
authenticatesaslStartsaslContinuegetnoncecreateUserupdateUsercopydbgetnoncecopydbsaslstartcopydbhelloisMaster
By default, the driver doesn't attach the
db.query.textattribute to command spans. Enable this attribute only when necessary.
警告
When you enable the db.query.text attribute, the driver includes the command text in span attributes, and your exporter sends the spans to your tracing backend. The tracing backend records filter values, query operators, and the contents of inserted or updated documents.
Error Handling
When an operation fails, the driver sets the status of both the operation span and its command span to Error. The driver records the exception details as span attributes that follow OpenTelemetry semantic conventions.
Some write errors, such as a duplicate key error, arrive in an otherwise successful command response. These errors don't set the command span's db.response.status_code attribute. The driver records them as exception attributes on the operation span instead.
错误并不会阻止驱动程序向您的应用程序抛出异常。
性能考虑因素
使用 OpenTelemetry 跟踪时,请考虑以下性能影响:
Capturing the
db.query.textattribute adds overhead. Capture command text only when necessary.If you don't configure an
ObservationRegistry, tracing has negligible performance impact, because the driver skips all tracing work.
要了解有关仪器性能权衡的更多信息,请参阅“性能”部分。 在 OpenTelemetry 文档中。
更多信息
要了解有关 OpenTelemetry 跟踪的更多信息,请参阅 OpenTelemetry Java 文档。 文档。
API 文档
要了解有关本指南中提到的类的更多信息,请参阅以下 API 文档: