为什么 NLog 不将范围数据记录到 Application Insights 自定义维度

Why is NLog not logging scope data to Application Insights custom Dimensions

我目前正在使用 nlog.config 文件中配置的 NLog 登录 Application Insights。我没有在任何地方设置 IncludeScopes(默认情况下为真)。

我正在尝试使用范围记录自定义属性。它在登录到文件或控制台时有效,但在登录到 Application Insights customDimensions 时无效。

这是我记录范围的方式:

using (_logger.BeginScope(new Dictionary<string, object> { ["ActivityId"] = Guid.NewGuid()})
{
    _logger.LogInformation("Logging from with scope");
}

这是 nlog.config 文件:

<target name="applicationInsights" xsi:type="ApplicationInsightsTarget" >
    <instrumentationKey>8d9f67d5-fe36-45cf-935f-2f87bb240b12</instrumentationKey>
    <!-- Only required if not using ApplicationInsights.config -->
    <contextproperty name="threadId" layout="${threadid}" />
    <contextproperty name="processName" layout="${processname}" />
    <!-- Can be repeated with more context -->
</target>

遗憾的是,我在 Application Insights 中查看 customDimensions 时没有看到 ActivityId。

我是 运行 我在 Azure 中的控制台应用程序,因此注册了一个辅助服务(处理消息),如下所示:

services.AddHostedService<PositionMessageProcessor>()

我需要做什么才能获取日志记录范围以在 Application Insights 中记录我的 ActivityId?

更新

我已经通过将 ActivityId 添加为特定 contextProperty 来记录它。我真的不想每次使用不同的属性调用 BeginScope(...) 时都必须更新配置文件。

有没有一种通用的方法让它适用于所有范围属性?

Is there a generic way to get it to work for all scope properties?

我假设你的意思是它将所有范围内的属性发送到应用程序洞察力而不指定哪些键。

目标目前不支持此功能,请参阅 source

在 NLog 4 中,范围属性被推送到 NestedDiagnosticsLogicalContext

您可以通过创建自己的目标来做到这一点:

  1. source
  2. 复制目标
  3. ApplicationInsightsTarget 内的 BuildPropertyBag 中循环 NestedDiagnosticsLogicalContext.GetAllObjects()
  4. 注册您的目标,参见NLog-Register your custom component

您可以使用 <contextproperty>JsonLayout 将范围上下文作为 blob 数据包含在内:

<target type="ApplicationInsightsTarget" name="aiTarget">
        <contextProperty name="scopeproperties">
            <layout type="JsonLayout" includeMdlc="true" />
        </contextProperty/>
</target>