Search code examples
c#azureazure-application-insightsnlogasp.net-core-3.1

Using nlog with ApplicationInsightsTelemetryWorkerService in .net core 3.1 console app


I'm configuring a .net core 3 console app with application insights and nlog

My code is configured as follows

Program.cs

 .ConfigureLogging((hostingContext, logging) =>
 {
     logging.ClearProviders();
     logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
     logging.AddNLog(NLog.LogManager.LoadConfiguration("nlog.config").Configuration);
 })
 .ConfigureServices((hostContext, services) =>
 {
      services.SetupConfiguration(hostContext.Configuration);
      services.AddApplicationInsightsTelemetryWorkerService("--AI-Key--");

In my nlog.config I have

  <extensions>
    <add assembly="NLog.Web.AspNetCore"/>
    <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
  </extensions>
 <!-- the targets to write to -->
  <targets>
    <target name="Console" xsi:type="Console"  layout="${longdate} ${level} ${message}"/>
    <target xsi:type="ApplicationInsightsTarget" name="appInsights" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <!--All logs, including from Microsoft-->
    <logger name="*" minlevel="Trace" writeTo="Console" />
    <logger name="*" minlevel="Trace" writeTo="appInsights" />
  </rules>

In appsettings.json I have

  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "--AI-Key--"
  },

In my code I use constructor injection to get the logger and then just

_logger.LogDebug("something");

Yet when I run this I'm not getting anything in application insights. I also notice in my output window I get some logs starting with:

Application Insights Telemetry (unconfigured): .....

There's not much documentation to go on unfortunately. Can anyone point me in the right direction.

Thanks very much.


Solution

  • Besides peter Bons' answer, here is one important thing you should know:

    The message Application Insights Telemetry (unconfigured): ..... means that the AI-key is not configured properly, so you cannot see the data float into appInsights.

    Please try add the AI-key in nlog.config, like below:

      <targets>
        <target name="Console" xsi:type="Console"  layout="${longdate} ${level} ${message}"/>
        <target xsi:type="ApplicationInsightsTarget" name="appInsights">
          <instrumentationKey>your_AI_Key</instrumentationKey>
        </target>
      </targets>
    

    I can repro your issue, if without add AI_Key in nlog.config; But works fine if add AI_Key in nlog.config.

    If you still have the issue, please provide a working sample code as well as these nuget packages and versions.