OpenTracing instrumentation for Mongo Driver.
pom.xml
<dependency>
<groupId>io.opentracing.contrib</groupId>
<artifactId>opentracing-mongo-driver</artifactId>
<version>VERSION</version>
</dependency>
pom.xml
<dependency>
<groupId>io.opentracing.contrib</groupId>
<artifactId>opentracing-mongo-driver-async</artifactId>
<version>VERSION</version>
</dependency>
pom.xml
<dependency>
<groupId>io.opentracing.contrib</groupId>
<artifactId>opentracing-mongo-driver-reactivestreams</artifactId>
<version>VERSION</version>
</dependency>
// Instantiate tracer
Tracer tracer = ...
// Optionally register tracer with GlobalTracer
GlobalTracer.register(tracer);
There are 2 ways to instrument MongoClient
:
- using Mongo Tracing Client
- using
MongoClientSettings.Builder
withTracingCommandListener
// Instantiate TracingCommandListener
TracingCommandListener listener = new TracingCommandListener.Builder(tracer).build()
// Instantiate Synchronous Tracing MongoClient
MongoClient mongoClient = new TracingMongoClient(listener, ...);
// Instantiate Asynchronous Tracing MongoClient
MongoClient mongoClient = new TracingAsyncMongoClient(listener, ...);
// Instantiate TracingCommandListener
TracingCommandListener listener = new TracingCommandListener.Builder(tracer).build()
// Add TracingCommandListener to MongoClientSettings.Builder
MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.addCommandListener(listener)
...
.build());
By default, span names are set to the operation performed by the Mongo client. To customize the span name, provide a MongoSpanNameProvider to the client that alters the span name. If a provider is not provided, the span name will remain the default.
// Create TracingCommandListener with custom span name provider
TracingCommandListener listener = new TracingCommandListener.Builder(tracer)\
.withSpanNameProvider(new PrefixSpanNameProvider("mongo."))
.build();
// Create TracingMongoClient
TracingMongoClient client = new TracingMongoClient(
listener,
replicaSetAddresses,
credentials,
clientOptions
);
Document doc = new Document();
client.getDatabase("db").getCollection("collection).insertOne(doc);
// Span name is now set to "mongo.insert"
To exclude specific Mongo commands from tracing add ExcludedCommand
to TracingCommandListener
:
List<ExcludedCommand> excludedCommands = new ArrayList<>();
ExcludedCommand excludedCommand = new ExcludedCommand();
excludedCommand.put("getMore", BsonNull.VALUE);
excludedCommand.put("collection", new BsonString("oplog.rs"));
excludedCommands.add(excludedCommand);
TracingCommandListener listener = new TracingCommandListener.Builder(tracer)
.withExcludedCommands(excludedCommands).build();