简体   繁体   中英

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

Just upgraded my application to the latest stable MongoDB C# Driver 2.0.

During the migration, basic functionality has been broken and even the simplest query like: this.collection.Find(e => e.Id == id).SingleOrDefaultAsync() doesn't return the correct data.

Checked the class mappings and conventions but I would like to see the output query in order to properly identify the issue.

So, how should it be done on the MongoClient side?

Setting profiling on the database level is possible but not a good solution since we have several applications and developers using the database.

My application is currently using Ninject.Extensions.Logging and log4net in the UI, business and EF data access.

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM