Para agentes de IA: um índice de documentação está disponível em https://www.mongodb.com/pt-br/docs/llms.txt — as versões de markdown de todas as páginas estão disponíveis anexando .md a qualquer caminho de URL.

Rastreie operações com OpenTelemetry

Neste guia, você aprenderá como usar o rastreamento OpenTelemetry com o driver Java. é uma estrutura de observabilidade de código aberto que fornece uma maneira padronizada de instrumentar, gerar, coletar e exportar dados de telemetria.

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.

Observação

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.

O driver não depende das bibliotecas Micrometer ou OpenTelemetry. Para usar o rastreamento, adicione as seguintes dependências ao seu aplicativo:

  • micrometer-tracing-bomLista de Materiais (BOM) do Micrômetro para Rastreamento. Gerencia versões compatíveis do Micrômetro e suas dependências de Rastreamento.

  • micrometer-observation: Provides the ObservationRegistry and the Micrometer Observation API.

  • micrometer-tracing-bridge-otelIntegração da observação micrométrica com a 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:

Adicione o seguinte código ao seu arquivo 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>

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>

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-actuator

  • micrometer-tracing-bridge-otel

  • opentelemetry-exporter-otlp

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

Observação

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()); } }

Configure a taxa de amostragem e o endpoint do exportador OTLP nas propriedades do seu aplicativo em vez de criar um SDK OpenTelemetry, conforme mostrado no exemplo a seguir:

management: tracing: sampling: probability: 1.0 otlp: tracing: endpoint: "http://localhost:4318/v1/traces"

Para saber mais, consulte Rastreamento. na documentação de referência do Spring Boot.

To configure tracing, use the following MicrometerObservabilitySettings.Builder methods:

Método
Argument Type
Descrição

observationRegistry()

ObservationRegistry

Define o registro que o driver usa para criar intervalos de rastreamento. Essa configuração é necessária para habilitar o rastreamento.

enableCommandPayloadTracing()

boolean

When set to true, the driver attaches the db.query.text attribute to command spans.

Padrão: false

maxQueryTextLength()

int

Sets the maximum length of the command text captured in the db.query.text attribute. The driver truncates longer command text to this length.

Padrão: Integer.MAX_VALUE (toda a carga útil do comando)

observationConvention()

ObservationConvention<MongodbObservationContext>

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 DefaultMongodbObservationConvention.

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();

Você também pode configurar as seguintes variáveis de ambiente no nível do driver:

  • OBSERVABILITY_MONGODB_ENABLED: Enables or disables tracing for every MongoClient instance that has an ObservationRegistry configured.

  • OBSERVABILITY_MONGODB_QUERY_TEXT_MAX_LENGTH: Sets the maximum length of the command text captured in the db.query.text attribute.

O driver Java cria os seguintes tipos de spans:

Tipo de Span
Descrição

mongodb.operation

Created for each user-initiated operation, such as find or insertOne.

mongodb.command

Criado para cada comando de protocolo de comunicação que o driver envia ao servidor. Os intervalos de comando são aninhados em seus respectivos intervalos de operação.

mongodb.transaction

Criada quando você inicia uma transação e finalizada quando a transação é confirmada ou cancelada.

Por exemplo, uma operação de busca cria um intervalo de nível de operação que contém um intervalo de nível de comando aninhado, conforme mostrado na seguinte hierarquia:

find sample_mflix.movies └── find

O driver Java segue as convenções semânticas do OpenTelemetry e inclui atributos que fornecem contexto sobre cada operação.

Os spans incluem os seguintes atributos gerais:

  • db.system.name: Sempre definido como mongodb

  • db.operation.name: Nome da operação de alto nível (apenas spans de operação)

  • db.operation.summary: Resumo da operação de alto nível (apenas spans de operação)

  • db.command.name: Nome do comando MongoDB (apenas spans de comando)

  • db.namespace: Nome do banco de dados

  • db.collection.name: Nome da coleção, quando aplicável

  • db.query.summary: Resumo da query (apenas spans de comando)

Os intervalos de comando incluem os seguintes atributos:

  • server.address: Host do servidor MongoDB

  • server.port: Porta do servidor MongoDB

  • network.transportProtocolo de transporte, como por exemplo: tcp

  • db.mongodb.server_connection_id: ID de conexão atribuída ao servidor

  • db.mongodb.driver_connection_id: ID de conexão atribuída ao driver

Quando aplicável, os intervalos de comando incluem os seguintes atributos:

  • db.mongodb.lsidID da sessão lógica

  • db.mongodb.txn_numberNúmero da transação

  • db.mongodb.cursor_idID do cursor, para operações que retornam cursores.

When you set enableCommandPayloadTracing to true, command spans include the following attribute:

  • db.query.textTexto do comando, truncado para o configurado maxQueryTextLength

Quando uma operação falha, o driver registra os detalhes da exceção como os seguintes atributos:

  • exception.type: Tipo da exceção

  • exception.message: Mensagem de exceção

  • exception.stacktrace: Rastreamento da pilha de exceções

  • db.response.status_code: Código de erro do MongoDB (apenas spans de comando)

O driver aplica as seguintes medidas de segurança para proteger informações confidenciais:

  • O driver não cria intervalos de comando para os seguintes comandos:

    • authenticate

    • saslStart

    • saslContinue

    • getnonce

    • createUser

    • updateUser

    • copydbgetnonce

    • copydbsaslstart

    • copydb

    • hello

    • isMaster

  • By default, the driver doesn't attach the db.query.text attribute to command spans. Enable this attribute only when necessary.

Aviso

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.

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.

Os erros não impedem o driver de gerar a exceção para sua aplicação.

Considere as seguintes implicações de desempenho ao usar o rastreamento OpenTelemetry:

  • Capturing the db.query.text attribute 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.

Para saber mais sobre as compensações de desempenho da instrumentação, consulte Desempenho. na documentação do OpenTelemetry.

Para saber mais sobre o rastreamento do OpenTelemetry, consulte a documentação do OpenTelemetry em Java. documentação.

Para saber mais sobre as classes mencionadas neste guia, consulte a seguinte documentação da API: