【问题标题】:Why is NLog not logging scope data to Application Insights custom Dimensions为什么 NLog 不将范围数据记录到 Application Insights 自定义维度
【发布时间】:2021-11-09 21:54:12
【问题描述】:

我目前正在使用在 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(...) 时都必须更新配置文件。

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

【问题讨论】:

标签: c# scope azure-application-insights nlog custom-dimensions


【解决方案1】:

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

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

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

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

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

  1. 从source复制目标
  2. 在BuildPropertyBag 中的NestedDiagnosticsLogicalContext.GetAllObjects() 中循环ApplicationInsightsTarget。
  3. 注册你的目标,见NLog-Register your custom component

【讨论】:

【解决方案2】:

您可以使用 &lt;contextproperty&gt; 和 JsonLayout 将范围上下文包含为 blob 数据:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 2022-01-06
    • 1970-01-01
    • 2012-09-07
    相关资源
    最近更新 更多