如何从控制台应用程序跟踪MongoDB请求 [英] How to track MongoDB requests from a console application

查看:58
本文介绍了如何从控制台应用程序跟踪MongoDB请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用C#编写的控制台应用程序项目,我在其中添加了Application Insights和以下NuGet软件包.

I have a Console Application project written in C# which I've added Application Insights to with the following NuGet packages.

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进行了启动:

I've configured my InstrumentationKey in the config file and I'm firing up a TelemetryClient on startup using the with the following code:

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 Server的请求,但没有任何其他外部请求的迹象.我有什么办法可以看到对Mongo的请求的遥测?

Everything is working well except AI is not capturing any requests that get sent to Mongo, I can see requests going off to SQL server in the 'Application map' but no sign of any other external requests. Is there any way that I can see telemetry of requests made to Mongo?

编辑-感谢Peter Bons,我最终得到了以下内容,这些内容像一种魅力,可以让我区分成功和失败:

EDIT - Thanks to Peter Bons I ended up with pretty much the following which works like a charm and allows me to distinguish between success and failure:

var telemetryClient = new TelemetryClient();
var connectionString = connectionStringSettings.ConnectionString;
var mongoUrl = new MongoUrl(connectionString);
var mongoClientSettings = MongoClientSettings.FromUrl(mongoUrl);

mongoClientSettings.ClusterConfigurator = clusterConfigurator =>
{
    clusterConfigurator.Subscribe<CommandSucceededEvent>(e =>
    {
        telemetryClient.TrackDependency("MongoDB", e.CommandName, DateTime.Now.Subtract(e.Duration), e.Duration, true);
    });

    clusterConfigurator.Subscribe<CommandFailedEvent>(e =>
    {
        telemetryClient.TrackDependency("MongoDB", $"{e.CommandName} - {e.ToString()}", DateTime.Now.Subtract(e.Duration), e.Duration, false);
    });
};

var mongoClient = new MongoClient(mongoClientSettings);

推荐答案

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

I am not familiar with MongoDB but as far as I can tell there is no default support for it when it comes to Application Insights. But that does not mean you cannot do this, it will just involve some more code.

同样,我不熟悉MongoDB,但根据 http://www.mattburkedev.com/logging-queries-from-mongodb-c-number-driver/内置了对生成的查询进行日志记录的支持.现在,我们只需要将其连接到Application Insights.

Again, I am not familiar with MongoDB but according to http://www.mattburkedev.com/logging-queries-from-mongodb-c-number-driver/ there is built-in support for logging the generated queries. Now, we only need to hook this up to Application Insights.

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

Since you already know how to use the TelemetryClient we can use the custom tracking methods provided by that class. See https://docs.microsoft.com/nl-nl/azure/application-insights/app-insights-api-custom-events-metrics for the available custom tracking methods.

您需要做的就是插入如下代码:

All you need to do is to insert some code like this:

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是线程安全的,因此您可以重用它.

The class telemetryClient is thread-safe so you can reuse it.

现在,根据所引用的博客文章,您应该能够执行以下操作:

Now, according to the referenced blogpost you should be able to do something like this:

var client = new MongoClient(new MongoClientSettings()
{
    Server = new MongoServerAddress("localhost"),
    ClusterConfigurator = cb =>
    {
        cb.Subscribe<CommandStartedEvent>(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的知识使它适应您的需求的想象的起点.

Again, I am not familiar with MongoDB but I hope this is a starting point for your imagination on how to adapt it to your needs using your knowledge of MongoDB.

如果与CommandStartedEvent事件相反还有一个CommandCompletedEvent或类似事件,则您可能应该在那里跟踪依赖项,因为这样您就可以计算(或简单读取)所花费的时间,并可能获得实际的指标的值.

If there is also a CommandCompletedEvent or similar event as opposed to the CommandStartedEvent event you should probably track the dependency there because you should then be able to calculate (or simpel read) the time spent and maybe get the actual value for the success indicator.

这篇关于如何从控制台应用程序跟踪MongoDB请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆