Skip to content
Switch branches/tags

OpenTracing instrumentation for Mongodb driver

This repository contains instrumentation for c# mongodb driver. It is doing instrumentation by hooking into mongo driver's database command events.

Build status OpenTracing Badge


Install-Package OpenTracing.Contrib.Mongo
dotnet add package OpenTracing.Contrib.Mongo


As a prerequisite, you need to have ITracer instance. Here you can find an example how to create Jaeger tracer instance. This is typically done once on application start.

ITracer tracer = ...

//If you are using using DI framework you can register tracer instance as singleton
//Also you can register with `GlobalTracer`

Once you have registered instance of a ITracer you can instantiate your mongo client with enabled instrumentation.

//Using default constructor
IMongoClient mongoClient = new TracingMongoClient();
IMongoClient mongoClient = new TracingMongoClient(GlobalTracer.Instance);

//By passing in connection string
IMongoClient mongoClient = new TracingMongoClient("<connection string>");
IMongoClient mongoClient = new TracingMongoClient(GlobalTracer.Instance, "<connection string>");

//By passing MongoUrl instance
IMongoClient mongoClient = new TracingMongoClient(new MongoUrl("..."));
IMongoClient mongoClient = new TracingMongoClient(GlobalTracer.Instance, new MongoUrl("..."));

//By passing `MongoClientSettings`
MongoClientSettings clientSettings = MongoClientSettings.FromConnectionString("<connection string>");
IMongoClient mongoClient = new TracingMongoClient(clientSettings);
IMongoClient mongoClient = new TracingMongoClient(GlobalTracer.Instance, clientSettings);

TracingMongoClient is instrumenting all mongo events. This can be changed by passing an optional constructor parameter.

var mongoClient = new TracingMongoClient("<connection string>", options =>
    options.WhitelistedEvents = new[] {"insert", "find"};


There are two samples in the /samples folder. One is the simple console application and one is the REST API which is already instrumented with OpenTracing.Contrib.NetCore instrumentation.

In order to run samples, you will need mongo database on default port and jaeger tracer. You can run jaeger with this docker command:

docker run -d --name jaeger \
  -p 5775:5775/udp \
  -p 6831:6831/udp \
  -p 6832:6832/udp \
  -p 5778:5778 \
  -p 16686:16686 \
  -p 14268:14268 \
  -p 9411:9411 \