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

10

我有一个用C#编写的控制台应用程序项目,我已经通过以下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<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);
1个回答

9

我不熟悉MongoDB,但据我所知,当涉及应用程序洞察时,它没有默认支持。但这并不意味着你不能做到这一点,只是需要编写更多的代码。

再次强调,我不熟悉MongoDB,但根据http://www.mattburkedev.com/logging-queries-from-mongodb-c-number-driver/的说法,内置支持记录生成的查询。现在,我们只需要将其连接到应用程序洞察即可。

由于您已经知道如何使用TelemetryClient,因此我们可以使用该类提供的自定义跟踪方法。有关可用的自定义跟踪方法,请参见https://learn.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<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的知识来适应它以满足你的需求的起点。

编辑:

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


3
如果你这样做了,也许应该创建一个Github仓库,并与全世界分享它? :) - John Gardner
很棒的回答,Peter。这不是GitHub上的那种东西,但我可能会写一篇博客文章介绍我正在做的事情,并将我最终得出的代码添加到我的问题中。 - Adam Cooper
现在有点晚了,但我终于写了那篇博客文章:https://sequence7.net/2017/02/09/monitoring-mongodb-with-application-insights/ - Adam Cooper
4
对于仍然对这个话题感兴趣的人 - 我已经创建了 GitHub 仓库和 Nuget,请查看 https://github.com/apostolsergii/DependencyTracking.MongoDb - Sergii Apostol

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接