如何通过NLog在AppInsights中获取范围信息?

问题描述

在将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中看到这一行:

enter image description here

我希望获得有关范围的信息;尽管我不知道它的外观,但我假设它是通过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": "@R_226_4045@ion"
    },"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"
      }
    ]
  }

有什么我想念的吗...?

解决方法

我想您可以尝试以下方法:

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

还创建了以下内容:https://github.com/microsoft/ApplicationInsights-dotnet/pull/2103