'NLog ApplicationInsights - Instrumentation Key from appsettings.json only loading for TelemetryClient

In my .NET 5 aspnetcore application, NLog is mostly working except for loading the Instrumentation Key from appsettings.json for the logger. It seems to be loading for the TelemetryClient just fine.

Program.cs:

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

...

Host.CreateDefaultBuilder(args)
  .ConfigureWebHostDefaults(webBuilder =>
  {
    webBuilder.UseStartup<Startup>();
  })
  .ConfigureLogging(logging =>
  {
    logging.ClearProviders();
  })
  .UseNLog();

NLog.config:

    <target xsi:type="ApplicationInsightsTarget" name="aiTarget">
        <instrumentationKey>${configsetting:item=AppInsights.InstrumentationKey}</instrumentationKey>
        <contextproperty name="threadid" layout="${threadid}" />
        <contextproperty name="AssemblyVersion" layout="${gdc:item=ExecutingAssembly-AssemblyVersion}" />
        <contextproperty name="FileVersion" layout="${gdc:item=ExecutingAssembly-FileVersion}" />
        <contextproperty name="ProductVersion" layout="${gdc:item=ExecutingAssembly-ProductVersion}" />
    </target>

appsettings.json:

  "AppInsights": {
    "ResourceName": "resource-name",
    "InstrumentationKey": "key"
  },

When I inspect the logger in debug mode this is what the InstrumentationKey for the logger is:

${configsetting:item=AppInsights.InstrumentationKey}

Logger InstrumentationKey

And the TelemetryClient is "key" like it should be:

TelemetryClient InstrumentationKey

If I leave it this way logs never make it to ApplicationInsights. But if I add this code to the Startup.cs the logs work as expected:

var aiTarget = LogManager.Configuration
  .FindTargetByName("aiTarget");

if (aiTarget is AsyncTargetWrapper wrapper &&
    wrapper.WrappedTarget is ApplicationInsightsTarget appInsightsTarget)
{
  appInsightsTarget.InstrumentationKey = configuration["AppInsights:InstrumentationKey"];
}

Am I doing something wrong?



Solution 1:[1]

I ran into the same problem with .NET 6 and the NLog ApplicationInsightsTarget. I worked around the issue just about the same way, except I also had to add this to reinitialize the log target:

LogManager.Configuration = LogManager.Configuration;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Buterbaugh