AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.

OpenTelemetry로 작업 추적

이 가이드에서는 Java 드라이버와 함께 OpenTelemetry 추적을 사용하는 방법을 알아볼 수 있습니다. 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.

이 드라이버는 Micrometer 또는 OpenTelemetry 라이브러리에 의존하지 않습니다. 추적 기능을 사용하려면 애플리케이션에 다음 종속성을 추가하십시오.

  • micrometer-tracing-bom: 마이크로미터 트레이싱 자재 명세서(BOM). 마이크로미터 및 마이크로미터 트레이싱 종속 항목의 호환 버전을 관리합니다.

  • micrometer-observation: Provides the ObservationRegistry and 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>

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:

참고

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

다음 예시와 같이 OpenTelemetry SDK를 빌드하는 대신 애플리케이션 속성에서 샘플링 속도와 OTLP 익스포터 엔드포인트를 구성하십시오.

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
설명

observationRegistry()

ObservationRegistry

드라이버가 추적 범위를 생성하는 데 사용하는 레지스트리를 설정합니다. 이 설정은 추적 기능을 활성화하는 데 필요합니다.

enableCommandPayloadTracing()

boolean

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

기본값입니다: 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.

기본값입니다: Integer.MAX_VALUE (전체 명령어 페이로드)

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

드라이버 수준에서 다음과 같은 환경 변수를 구성할 수도 있습니다.

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

Java 드라이버는 다음과 같은 유형의 스팬을 생성합니다.

스팬 유형
설명

mongodb.operation

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

mongodb.command

드라이버가 서버로 전송하는 각 와이어 프로토콜 명령에 대해 생성됩니다. 명령 스팬은 해당 작업 스팬 아래에 중첩됩니다.

mongodb.transaction

트랜잭션을 시작할 때 생성되고, 트랜잭션이 완료되거나 중단될 때 종료됩니다.

예를 들어, 찾기 작업은 다음 계층 구조에 표시된 것처럼 중첩된 명령 수준 스팬을 포함하는 작업 수준 스팬을 생성합니다.

find sample_mflix.movies └── find

Java 드라이버는 OpenTelemetry의 의미론적 규칙을 따르며 각 작업에 대한 컨텍스트를 제공하는 속성을 포함합니다.

스팬에는 다음과 같은 일반 속성이 포함됩니다.

  • db.system.name: 항상 다음으로 설정하다 mongodb

  • db.operation.name: 상위 수준 작업의 이름(작업 스팬만 해당)

  • db.operation.summary: 상위 수준 작업 요약(작업 스팬만 해당)

  • db.command.name: MongoDB 명령 이름(명령 범위에만 해당)

  • db.namespace: 데이터베이스 이름

  • db.collection.name: 컬렉션 이름(해당되는 경우)

  • db.query.summary: 쿼리 요약(명령 범위만 해당)

명령 범위에는 다음과 같은 속성이 포함됩니다.

  • server.address: MongoDB 서버 호스팅하다

  • server.port: MongoDB 서버 포트

  • network.transport: 전송 프로토콜(예: ...) tcp

  • db.mongodb.server_connection_id: 서버에서 할당한 연결 ID

  • db.mongodb.driver_connection_id: 드라이버 할당 연결 ID

해당되는 경우, 명령 범위에는 다음과 같은 속성이 포함됩니다.

  • db.mongodb.lsid논리적 세션 ID

  • db.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 오류 코드(명령 범위에만 해당)

드라이버는 민감한 정보를 보호하기 위해 다음과 같은 보안 조치를 적용합니다.

  • 드라이버는 다음 명령에 대한 명령 스팬을 생성하지 않습니다.

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

경고

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.

오류가 발생하더라도 드라이버는 예외를 애플리케이션에 발생시킬 수 있습니다.

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.

계측 장비의 성능 절충점에 대한 자세한 내용은 성능 섹션을 참조하십시오. OpenTelemetry 문서에 나와 있습니다.

OpenTelemetry 추적에 대한 자세한 내용은 OpenTelemetry Java 문서를 참조하세요. 선적 서류 비치.

이 가이드에 언급된 클래스에 대한 자세한 내용은 다음 API 문서를 참조하십시오.