NLog ApplicationInsightsTarget 无法从 appsettings.json 读取应用程序见解密钥

NLog ApplicationInsightsTarget unable to read application insights key from appsettings.json

我正在尝试从我的 ASP.NET 核心 3.1 Web 应用程序中的 appsettings.json 文件中读取应用程序洞察检测密钥,但我的所有尝试都没有成功,因为目标仍显示为未配置.

如果我直接在 ApplicationInsightsTarget 中添加密钥,那么它工作正常。

这里是appsettings.json文件的内容:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "AppInsightsKey": "Instrumentation-Key-From-Azure-Application-Insights-Resource"
}

这里是nlog.config文件的内容:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwConfigExceptions="true"
      internalLogLevel="info"
      internalLogFile="c:\temp\internal-nlog-AspNetCore3.txt">

  <!-- enable asp.net core layout renderers -->
  <extensions>
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
    <add assembly="NLog.Web.AspNetCore"/>
  </extensions>

  <!-- the targets to write to -->
  <targets>       

    <!--Console Target for hosting lifetime messages to improve Docker / Visual Studio startup detection -->
    <target xsi:type="Console" name="lifetimeConsole" layout="${configsetting:item=AppInsightsKey} ${level:truncate=4:lowercase=true}: ${logger}[0]${newline} ${message}${exception:format=tostring}" />
    
    <target name="aiTarget" xsi:type="ApplicationInsightsTarget"
     layout="${date:format=yyyy-MM-dd HH\:mm\:ss}: [LOCAL] - ${level} - ${message}${exception:format=ToString}">
      <instrumentationKey>${configsetting:item=AppInsightsKey}</instrumentationKey>
      <contextproperty name="threadid" layout="${threadid}" />
    </target>
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>      
    <logger name="*" minlevel="Trace" writeTo="lifetimeConsole" />
    <logger name="*" minlevel="Trace" writeTo="aiTarget" />
  </rules>
</nlog>

正如您从上面看到的,我试图通过 ${configsetting:item=AppInsightsKey} 从 appsettings.json 文件中获取应用程序洞察密钥,但在所有情况下它都是空的。

我试过 ${configsetting:name=AppInsightsKey} ,也没有用。

这是program.cs文件内容

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;

namespace ASPNETCoreWebAppNLogAppInsightsDemo
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
            try
            {
                logger.Debug("init main");
                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                NLog.LogManager.Shutdown();
            }
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
          webBuilder.UseStartup<Startup>();
      })
      .ConfigureLogging(logging =>
      {
          logging.ClearProviders();
          logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
      })
      .UseNLog();  // NLog: Setup NLog for Dependency injection
    }
}

然后我尝试将密钥嵌入到控制台目标布局中,只是为了确保 nlog 能够正确读取它,令我惊讶的是它运行得非常好。因此,看起来问题仅出在 ApplicationInsightsTarget 上。

我知道,我可以从环境变量中提取它,因此在 Azure 应用服务中不需要从 appsettings.json 读取,但我想了解这种行为,因为已经花了太多时间修复我自己 :-)

任何帮助将不胜感激。

尝试替换旧代码:

var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();

使用这个新代码:

    var logger = LogManager.Setup()
                           .LoadConfigurationFromAppSettings()
                           .GetCurrentClassLogger();

新代码将加载 appsettings.json,并确保 ${configsetting} 在 NLog 目标初始化期间可用。