如何在MongoDB C#Driver 2.0中记录查询? [英] How do I log my queries in MongoDB C# Driver 2.0?
问题描述
只需将我的应用程序升级到最新的稳定的MongoDB C#Driver 2.0.
Just upgraded my application to the latest stable MongoDB C# Driver 2.0.
在迁移过程中,基本功能已被破坏,即使是最简单的查询,例如:this.collection.Find(e => e.Id == id).SingleOrDefaultAsync()
,也不会返回正确的数据.
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.
那么,应该如何在MongoClient
一侧完成此操作?
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.
我的应用程序当前在UI,业务和EF数据访问中使用Ninject.Extensions.Logging
和log4net
.
My application is currently using Ninject.Extensions.Logging
and log4net
in the UI, business and EF data access.
推荐答案
对于较新的C#MongoDB驱动程序,API已更改.您必须使用接受MongoClientSettings
对象而不是连接字符串的更复杂的构造函数.
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);
这篇关于如何在MongoDB C#Driver 2.0中记录查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!