【问题标题】:How to get scoped information in AppInsights via NLog?如何通过 NLog 在 AppInsights 中获取范围信息?
【发布时间】:2020-10-30 12:08:17
【问题描述】:

在构造函数中注入ILogger<> 的方法中考虑以下代码:

using (_logger.BeginScope("Requesting {page} for {identification}", page, identification))
{
    if (identification == null)
    {
        var test = "Test String";
        _logger.LogTrace("No identification present {test}. Presenting Index page", test);
        return Page();
    }

    _logger.LogDebug("Identification present: {identification}", identification);
}

我在 AI 中看到了这一行:

我希望获得有关范围的一些信息;虽然我不知道它是什么样子,但我认为它是沿着 LoggerNametest 属性添加到 CustomDimensions 中的。

在我的创业课程中,我有这个:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<ApplicationInsightsServiceOptions>(Configuration.GetSection("ApplicationInsights"));
    services.AddApplicationInsightsTelemetry();
    LogManager.Configuration = new NLogLoggingConfiguration(Configuration.GetSection("NLog"));

    /// ... the reset
}

我的 appsettings.json 看起来像这样:

{
  "Logging": {
    "IncludeScopes": true,
    "NLog": {
      "IncludeScopes": true
    },
    "LogLevel": {
      "Default": "Trace",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    },
    "ApplicationInsights": {
      "IncludeScopes": true,
      "LogLevel": {
        "Default": "Trace"
      }
    }
  },
  "NLog": {
    "autoReload": true,
    "throwConfigExceptions": true,
    "internalLogLevel": "trace",
    "internalLogFile": "${basedir}/internal-nlog.txt",
    "extensions": [
      {
        "assembly": "Microsoft.ApplicationInsights.NLogTarget"
      }
    ],
    "targets": {
      "aiTarget": {
        "type": "ApplicationInsightsTarget"
      },
      "logconsole": {
        "type": "ColoredConsole"
      }
    },
    "rules": [
      {
        "logger": "*",
        "minLevel": "Trace",
        "writeTo": "aiTarget, logconsole"
      }
    ]
  }

我有什么遗漏的吗...?

【问题讨论】:

    标签: asp.net-core azure-application-insights nlog


    【解决方案1】:

    我想你可以试试这个:

        "targets": {
          "aiTarget": {
            "type": "ApplicationInsightsTarget",
            "contextproperties": [
            {
                "name": "scopecontext",
                "layout": {
                    "type": "JsonLayout",
                    "includemdlc": "true"
                }
            }]
          },
          "logconsole": {
            "type": "ColoredConsole"
          }
        },
    

    还创建了这个:https://github.com/microsoft/ApplicationInsights-dotnet/pull/2103

    【讨论】:

    • 哇,它有效!我非常感谢您的回答 :-) 但我不知道如果没有您的知识,我怎么可能解决这个问题,这可能纯粹是经验。您的 PR 是否像文档所暗示的那样使其开箱即用?那么,如果 PR 获得批准,配置更改可以恢复为具有相同的功能吗?
    • @321X 是的,PR 将允许在没有 JsonLayout 帮助的情况下捕获范围上下文
    猜你喜欢
    • 2017-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多