gpt4 book ai didi

.net - 与 Azure Application Insights、ASP.NET MVC 和 NLog 的事件关联

转载 作者:行者123 更新时间:2023-12-02 23:00:30 38 4
gpt4 key购买 nike

如何设置混音?我在配置 Application InsightsNLog 时没有遇到任何问题,但我不知道如何关联操作。我使用最新版本的 NLog,因此它可以识别 System.Diagnostics.Trace.CorrelationManager.ActivityId 及其 ${activityid} 变量。另一方面,Application Insights 使用它自己的关联机制。我的问题是:

  1. 谁负责初始化标准 Trace.CorrelationManager.ActivityId?我以为它是 ASP.NET MVC,但在调试器中它始终是 Guid.Empty。如果由我决定,MVC 管道中生成 id 的最佳位置在哪里?
  2. 如何使 Application Insights 使用 Trace.CorrelationManager.ActivityId?或者,让 NLog 使用 Aplication Insights 的内部关联 ID?
  3. 如何确保 ID 在任何 Task.Run()await 调用中正确传播/恢复?

更新:

这是我最终将 AI 链接到 NLog 的结果:

    private void Log(LogEventInfo lei)
{
lei.Properties["OperationId"] = CorrelationManager.GetOperationId();
this.logger.Log(lei);
}

这是对 NLogLog() 方法的包装,它添加了一个可以在 NLog.config 中引用为 ${event-context:操作ID}CorrelationManager 这里是 @Aravind 提供的链接中的解决方案。系统CallContext的使用保证了操作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 core 应用程序中使用 Application Insights 2.1+(也可能是 .net 框架,但我尚未测试),它们会自动设置 System.Diagnostics.Activity.Current到包含您可能需要的所有 Application Insights 信息以及更多信息的对象 ( ref )。

在代码中您可以使用System.Diagnostics.Activity.Current?.IdSystem.Diagnostics.Activity.Current?.RootId 。 (使用调试器检查 Activity.Current 以查看还有什么并了解不同的 nlog 标签将输出什么)

要使用 nlog 记录它,您可以使用 NLog.DiagnosticSource package :

  1. 安装软件包

    Install-Package NLog.DiagnosticSource或在您的 csproj 中:

    <PackageReference Include="NLog.DiagnosticSource" Version="1.*" />
  2. 添加到您的 nlog.config:

    <extensions>
    <add assembly="NLog.DiagnosticSource"/>
    </extensions>
  3. 添加到 nlog 目标:

使用${activity:property=TraceId} (或用 Id 代替 TraceId,或 many other properties they list 之一)在 <target> 中,例如:

<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

关于.net - 与 Azure Application Insights、ASP.NET MVC 和 NLog 的事件关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39471664/

38 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com