boberneprotiv.com

How to log mongodb queries in c#/asp.net

Tracking database queries is a common task for any web application. Most obvious reason is to debug internal processes, but it is also useful to track external queries, especially database queries, to see which queries are taking the most time, and where to focus optimization efforts.

Thankfully, the official MongoDB driver for .NET/C# has API that makes it easy to track database queries. MongoClientSettings expose ClusterConfigurator property that allows you to configure the driver to subscribe to various events. For our purposes, we will use CommandStartedEvent, CommandSucceededEvent, and CommandFailedEvent to track beginning, success end, and failure of database queries.

Here is simple console project that demonstrates how to use it:

using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Core.Events;

var settings = MongoClientSettings.FromConnectionString("mongodb://localhost:27017");

settings.ClusterConfigurator = builder =>
{
    builder.Subscribe<CommandStartedEvent>(e =>
    {
        Console.WriteLine($"Mongodb query started: {e.Command.ToJson()}");
    });

    builder.Subscribe<CommandSucceededEvent>(e =>
    {
        Console.WriteLine($"Mongodb query finished in {e.Duration.Milliseconds}ms");
    });

    builder.Subscribe<CommandFailedEvent>(e =>
    {
        Console.WriteLine($"Mongodb query failed in {e.Duration.Milliseconds}ms");
    });
};

var client = new MongoClient(settings);
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("test");
collection.InsertOne(new BsonDocument("test", 1));
collection.Find(new BsonDocument()).ToList();

And here is output of the program:

Mongodb query started: { "isMaster" : 1, "helloOk" : true, "client" : { "driver" : { "name" : "mongo-csharp-driver", "version" : "2.19.0.0" }, "os" : { "type" : "xxx", "name" : "xxx", "architecture" : "xxx", "version" : "xxx" }, "platform" : ".NET 7.0.2" }, "compression" : [] }
Mongodb query finished in 12ms
Mongodb query started: { "insert" : "test", "ordered" : true, "$db" : "test", "lsid" : { "id" : CSUUID("af73792c-b1d8-4b3f-a5e4-13dbfdfe70bc") }, "documents" : [{ "_id" : ObjectId("6408e85b937b00842ee9a0cb"), "test" : 1 }] }
Mongodb query finished in 29ms
Mongodb query started: { "find" : "test", "filter" : { }, "$db" : "test", "lsid" : { "id" : CSUUID("af73792c-b1d8-4b3f-a5e4-13dbfdfe70bc") } }
Mongodb query finished in 2ms