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

标签 c# mongodb visual-studio azure azure-application-insights

我有一个用 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 Server,但没有任何其他外部请求的迹象。有什么方法可以查看向 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);

最佳答案

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

再说一遍,我对 MongoDB 并不熟悉,但根据http://www.mattburkedev.com/logging-queries-from-mongodb-c-number-driver/内置支持记录生成的查询。现在,我们只需将其连接到 Application Insights。

由于您已经知道如何使用 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 事件,您可能应该跟踪那里的依赖关系,因为您应该能够计算(或简单地阅读)花费的时间,也许可以获得成功指标的实际值。

关于c# - 如何从控制台应用程序跟踪 MongoDB 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41806029/

相关文章:

mongodb - 插入 MongoDB 并存储 ObjectID?

c# - 动态磁贴更新

c# - JSON 从 unicode 到原始格式的转换

c# - 队列将项目移回末尾

c# - Visual Studio 编译器错误(不能使用逗号)

visual-studio - 为什么在 VS 2019 中出现智能错误

c++ - 将Qt集成到现有VS项目中以替换WinAPI

c# - 结构 - System.Runtime.Interoptservice C++ 与 C#

javascript - MeteorJS 和 x-editable-reactive-template

node.js - 无法加载资源: the server responded with a status of 431 (Request Header Fields Too Large)