Logging Queries from MongoDB C# Driver

I searched all over and found only a few out of date examples for setting up the MongoDB driver to log queries and only found small hints in the comments of StackOverflow questions or references to older versions that don’t apply anymore.

Anyway, here’s what I’ve found to work with in MongoDriver 2+

You’ll have to use the more verbose MongoClient constructor, but you can subscribe to events using the ClusterConfigurator option:

LoggingMongo.cs
var client = new MongoClient(new MongoClientSettings() { Server = new MongoServerAddress("localhost"), ClusterConfigurator = cb => { cb.Subscribe<CommandStartedEvent>(e => { Console.WriteLine($"{e.CommandName} - {e.Command.ToJson()}"); }); } });

Using the configurator’s Subscribe method, we attach to the stream of CommandStartedEvents. There are a few other event types you can subscribe to, but this one seems the most helpful for our current needs.

You’ll get stuff like this logged:

mongolog.txt
isMaster - { "isMaster" : 1, "client" : { "driver" : { "name" : "mongo-csharp-driver", "version" : "2.4.0.70" }, "os" : { "type" : "Windows", "name" : "Microsoft Windows 10.0.14393", "architecture" : "x86_32", "version" : "10.0.14393" }, "platform" : ".NET Framework 4.0.0.0" } } buildInfo - { "buildInfo" : 1 } getLastError - { "getLastError" : 1 } isMaster - { "isMaster" : 1 } buildInfo - { "buildInfo" : 1 } isMaster - { "isMaster" : 1, "client" : { "driver" : { "name" : "mongo-csharp-driver", "version" : "2.4.0.70" }, "os" : { "type" : "Windows", "name" : "Microsoft Windows 10.0.14393", "architecture" : "x86_32", "version" : "10.0.14393" }, "platform" : ".NET Framework 4.0.0.0" } } buildInfo - { "buildInfo" : 1 } getLastError - { "getLastError" : 1 } findAndModify - { "findAndModify" : "classes", "query" : { "Code" : "CS321", "Students.Name" : "Bob" }, "update" : { "$set" : { "Students.$.Grade" : 95 } } } find - { "find" : "classes", "filter" : { "Code" : "CS321" }, "limit" : 1 }

You’ll get more events passed to you than you probably care about, like “isMaster”, “buildInfo”, and “getLastError”. You can filter them using the CommandName property.