在 .net core 3.1 控制台应用程序中将 nlog 与 ApplicationInsightsTelemetryWorkerService 结合使用

Sue*_*rsi 7 c# nlog azure azure-application-insights asp.net-core-3.1

我正在使用应用程序见解和 nlog 配置 .net core 3 控制台应用程序

我的代码配置如下

程序.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--");
Run Code Online (Sandbox Code Playgroud)

在我的 nlog.config 中我有

  <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>
Run Code Online (Sandbox Code Playgroud)

在 appsettings.json 我有

  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "--AI-Key--"
  },
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我使用构造函数注入来获取记录器,然后

_logger.LogDebug("something");
Run Code Online (Sandbox Code Playgroud)

然而,当我运行这个程序时,我没有获得任何应用程序见解。我还注意到在我的输出窗口中我得到了一些以以下开头的日志:

Application Insights Telemetry (unconfigured): .....
Run Code Online (Sandbox Code Playgroud)

不幸的是,没有太多的文档可以继续。谁能指出我正确的方向。

非常感谢。

Iva*_*ang 6

除了彼得·邦斯的回答之外,您还应该知道以下一件重要的事情:

该消息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>
Run Code Online (Sandbox Code Playgroud)

如果没有在 nlog.config 中添加 AI_Key,我可以重现您的问题;但如果在 nlog.config 中添加 AI_Key 则可以正常工作。

如果您仍然遇到问题,请提供有效的示例代码以及这些 nuget 软件包和版本。