如何在MongoDB C#Driver 2.0中记录我的查询?

时间:2015-05-19 18:56:49

标签: c# mongodb logging mongodb-.net-driver mongodb-csharp-2.0

刚刚将我的应用程序升级到最新的稳定版MongoDB C#Driver 2.0。

在迁移过程中,基本功能已被破坏,即使是最简单的查询,例如:this.collection.Find(e => e.Id == id).SingleOrDefaultAsync()也无法返回正确的数据。

检查了类映射和约定,但我希望看到输出查询以正确识别问题。

那么,应该如何在MongoClient方面完成?

在数据库级别设置分析是可能的,但不是一个好的解决方案,因为我们有几个应用程序和开发人员使用数据库。

我的应用程序目前在UI,业务和EF数据访问中使用Ninject.Extensions.Logginglog4net

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

你可以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));
    }
};

如果愿意,可以将它连接到log4net。

答案 2 :(得分:0)

使用2.7.3驱动程序登录到VS输出。

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