Activity correlation with Azure Application Insights, ASP.NET MVC and NLog(与Azure应用程序洞察、ASP.NET MVC和NLog的活动关联)
问题描述
如何设置组合?配置Application Insights和NLog没有问题,但我不知道如何关联操作。我使用最新版本的NLog,因此它知道System.Diagnostics.Trace.CorrelationManager.ActivityId及其${activityid}变量。另一方面,应用程序洞察使用它自己的关联机制。我的问题是:
- 谁负责初始化标准Trace.CorrelationManager.ActivityId?我以为它是ASP.NETMVC,但在调试器中它总是Guid.Empty。如果由我决定,MVC管道中生成id的最佳位置在哪里?
- 如何使应用程序洞察使用Trace.CorrelationManager.ActivityId?或者,使NLog使用应用程序洞察‘内部关联ID?
- 如何确保在任何Task.Run()和await调用中正确传播/恢复ID?
更新:
以下是我最终将AI链接到NLog的结果:
    private void Log(LogEventInfo lei)
    {
        lei.Properties["OperationId"] = CorrelationManager.GetOperationId();
        this.logger.Log(lei);
    }
这是NLog的Log()方法的包装器,该方法添加了一个可在NLog.config中作为${event-context:OperationId}引用的属性。CorrelationManager以下是@Aravind提供的链接的解决方案。使用SystemCallContext可确保操作ID将流经所有异步点。现在,我们需要获取AI操作ID并将其存储在CorrelationManager中。这在Global.asax.cs:
protected void Application_BeginRequest()
{
    RequestTelemetry telemetry = HttpContext.Current.GetRequestTelemetry();
    string operationId = telemetry?.Id ?? Guid.NewGuid().ToString();
    CorrelationManager.SetOperationId(operationId);
}
现在,如果为您的应用程序启用了AI,您的NLog日志将与AI日志相关联。
推荐答案
如果您在.Net核心应用程序(可能也是.Net框架,但我还没有测试过)中使用Application Insights 2.1+,它们会自动将System.Diagnostics.Activity.Current设置为一个对象,该对象包含您需要的所有Application Insights信息以及更多信息(ref)。
在代码中可以使用System.Diagnostics.Activity.Current?.Id或System.Diagnostics.Activity.Current?.RootId。(使用调试器检查Activity.Current以查看其他内容&了解不同的nlog标记将输出的内容)
要使用nlog记录它,请使用NLog.DiagnosticSource package:
- 安装程序包 - Install-Package NLog.DiagnosticSource或您的csproj:- <PackageReference Include="NLog.DiagnosticSource" Version="1.*" />
- 添加到您的nlog.config: - <extensions> <add assembly="NLog.DiagnosticSource"/> </extensions>
- 添加到nlog目标: 
在<target>中使用${activity:property=TraceId}(或ID代替TraceID,或many other properties they list之一),例如:
<extensions>
    <add assembly="NLog.DiagnosticSource"/>
</extensions>
<targets>
    <target name="console" xsi:type="console" layout="${message}|TraceId=${activity:property=TraceId}" />
</targets>
<rules>
    <logger minLevel="Info" writeTo="console" />
</rules>
这将输出类似以下内容的日志消息:
My log message|TraceId=921af8f6ba994c9eb3832ebf200846d7
或使用Id而不是TraceId
My log message|Id=00-921af8f6ba994c9eb3832ebf200846d7-0e8ba5571915864b-00
这篇关于与Azure应用程序洞察、ASP.NET MVC和NLog的活动关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:与Azure应用程序洞察、ASP.NET MVC和NLog的活动关联
 
				
         
 
            
        - 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
 
						 
						 
						 
						 
						 
				 
				 
				 
				