How do I log my queries in MongoDB C# Driver 2.0?

For newer C# MongoDB drivers the API has changed. You have to use the more complex constructor that accepts a MongoClientSettings object, instead of the connection string.

Use the following code to keep using a connection string, but enable the logging of each command:

var mongoConnectionUrl = new MongoUrl(connectionString);
var mongoClientSettings = MongoClientSettings.FromUrl(mongoConnectionUrl);
mongoClientSettings.ClusterConfigurator = cb => {
    cb.Subscribe<CommandStartedEvent>(e => {
        logger.Log($"{e.CommandName} - {e.Command.ToJson()}");
    });
};
var mongoCfgClient = new MongoClient(mongoClientSettings);

You can enable logging by the mongo driver itself:

var settings = new MongoClientSettings
{
    ClusterConfigurator = cb =>
    {
        var textWriter = TextWriter.Synchronized(new StreamWriter("mylogfile.txt"));
        cb.AddListener(new LogListener(textWriter));
    }
};

You can hook it up to log4net if you wish.


Logging to VS output with 2.7.3 driver.

using MongoDB.Bson;
using MongoDB.Driver;
using System;
#if TRACE
using System.Diagnostics;
using MongoDB.Driver.Core.Configuration;
#endif

...

public static ClusterBuilder ConfigureCluster(ClusterBuilder builder)
{
#if TRACE
    var traceSource = new TraceSource(nameof(Geotagging), SourceLevels.Verbose);
    builder.TraceWith(traceSource);
    builder.TraceCommandsWith(traceSource);
#endif
    return builder;
}

public MongoClient BuildMongoClient(string connection_string)
{
    var mongoUrlBuilder = new MongoUrlBuilder(connection_string);
    var settings = MongoClientSettings.FromUrl(mongoUrlBuilder.ToMongoUrl());
    settings.ClusterConfigurator = cb => ConfigureCluster(cb);
    return new MongoClient(settings);
}