如何从控制台应用程序跟踪MongoDB请求

我有一个用C#编写的Console Application项目,我已经使用以下NuGet包添加了Application Insights。

Microsoft.ApplicationInsights Microsoft.ApplicationInsights.Agent.Intercept Microsoft.ApplicationInsights.DependencyCollector Microsoft.ApplicationInsights.NLogTarget Microsoft.ApplicationInsights.PerfCounterCollector Microsoft.ApplicationInsights.Web Microsoft.ApplicationInsights.WindowsServer Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel 

我已经在配置文件中配置了InstrumentationKey,并且我在启动时使用以下代码启动了TelemetryClient:

 var telemetryClient = new TelemetryClient(); telemetryClient.Context.User.Id = Environment.UserName; telemetryClient.Context.Session.Id = Guid.NewGuid().ToString(); telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString(); 

一切都运行良好,除了AI没有捕获任何发送到Mongo的请求,我可以看到请求在“应用程序映射”中发送到SQL服务器,但没有任何其他外部请求的迹象。 有什么方法可以看到对Mongo的请求的遥测?

编辑 – 感谢Peter Bons,我最终得到了以下几个像魅力一样的东西,让我能够区分成功和失败:

 var telemetryClient = new TelemetryClient(); var connectionString = connectionStringSettings.ConnectionString; var mongoUrl = new MongoUrl(connectionString); var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl); mongoClientSettings.ClusterConfigurator = clusterConfigurator => { clusterConfigurator.Subscribe(e => { telemetryClient.TrackDependency("MongoDB", e.CommandName, DateTime.Now.Subtract(e.Duration), e.Duration, true); }); clusterConfigurator.Subscribe(e => { telemetryClient.TrackDependency("MongoDB", $"{e.CommandName} - {e.ToString()}", DateTime.Now.Subtract(e.Duration), e.Duration, false); }); }; var mongoClient = new MongoClient(mongoClientSettings); 

我不熟悉MongoDB,但据我所知,在Application Insights方面没有默认支持。 但这并不意味着你不能这样做,它只会涉及更多的代码。

同样,我不熟悉MongoDB,但根据http://www.mattburkedev.com/logging-queries-from-mongodb-c-number-driver/ ,内置支持记录生成的查询。 现在,我们只需要将其与Application Insights联系起来。

由于您已经知道如何使用TelemetryClient我们可以使用该类提供的自定义跟踪方法。 有关可用的自定义跟踪方法,请参阅https://docs.microsoft.com/nl-nl/azure/application-insights/app-insights-api-custom-events-metrics 。

您需要做的就是插入一些代码:

 telemetryClient.TrackDependency( "MongoDB", // The name of the dependency query, // Text of the query DateTime.Now, // Time that query is executed TimeSpan.FromSeconds(0), // Time taken to execute query true); // Indicates success 

telemetryClient类是线程安全的,因此您可以重用它。

现在,根据引用的博客文章,您应该能够做到这样的事情:

 var client = new MongoClient(new MongoClientSettings() { Server = new MongoServerAddress("localhost"), ClusterConfigurator = cb => { cb.Subscribe(e => { telemetryClient.TrackDependency( "MongoDB", // The name of the dependency e.Command.ToJson() // Text of the query DateTime.Now, // Time that query is executed TimeSpan.FromSeconds(0), // Time taken to execute query true); // Indicates success }); } }); 

同样,我对MongoDB并不熟悉,但我希望这是你想象中如何根据你的MongoDB知识使其适应你的需求的起点。

编辑:

如果还存在CommandCompletedEvent或类似事件而不是CommandStartedEvent事件,那么您应该跟踪那里的依赖关系,因为您应该能够计算(或简化读取)所花费的时间,并且可能获得成功指标的实际值。