首页 > 解决方案 > 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.

标签: c#azureazure-application-insightsnlogasp.net-core-3.1

解决方案


除了 peter Bons 的回答之外,您还应该知道一件重要的事情:

该消息Application Insights Telemetry (unconfigured): .....表示 AI-key 配置不正确,因此您看不到数据浮动到 appInsights 中。

请尝试在 中添加 AI-key nlog.config,如下所示:

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

如果没有在 nlog.config 中添加 AI_Key,我可以重现您的问题;但是如果在 nlog.config 中添加 AI_Key 就可以了。

如果您仍有问题,请提供工作示例代码以及这些 nuget 包和版本。


推荐阅读