在.NET Core 3.1控制台应用中使用nlog和ApplicationInsightsTelemetryWorkerService

7
我正在配置一个带有应用程序洞察和nlog的.net core 3控制台应用程序
我的代码配置如下
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--");

在我的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>

在 appsettings.json 文件中,我有如下内容:
  "Logging": {
    "LogLevel": {
      "Default": "Debug"
    }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "--AI-Key--"
  },

在我的代码中,我使用构造函数注入获取日志记录器,然后只需...
_logger.LogDebug("something");

然而,当我运行这个时,在应用洞察中没有得到任何东西。我还注意到在我的输出窗口中,我获得了一些以以下方式开头的日志:
Application Insights Telemetry (unconfigured): .....

很遗憾没有太多的文档可供参考。有人可以指引我正确的方向吗?
非常感谢。

请问您能否提供一个可用的示例代码,以及您使用的NuGet包是哪个? - Ivan Glasenberg
2个回答

6

除了Peter Bons的答案,这里还有一件你需要知道的重要事情:

消息Application Insights Telemetry (未配置): .....表示AI-key没有正确配置,因此你无法看到数据流入appInsights。

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

  <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包和版本。


谢谢,这对我很有帮助。你知道有没有一种动态设置的方法吗?比如说,如果你想在每个环境中使用不同的密钥。 - Suemayah Eldursi
1
我通过以下方式成功动态设置它: var appInsightsTarget = NLog.LogManager.Configuration.FindTargetByName<ApplicationInsightsTarget>("appInsights"); 然后 appInsightsTarget.InstrumentationKey = instrumentationKey; - Suemayah Eldursi
应该可以使用NLog布局渲染器来处理"InstrumentationKey"。这样你就可以查找设置/环境变量/等等。 - Rolf Kristensen

3
请注意,设置Application Insights的日志级别是通过在logging部分内使用名为ApplicationInsights的部分来完成的:
"Logging": {
    "LogLevel": {
      "Default": "Debug",
    "ApplicationInsights"
       "LogLevel": {
           "Default": "Debug"
       }
     }
  },
  "ApplicationInsights": {
    "InstrumentationKey": "--AI-Key--"
  }

因此,您的当前设置将无法获取调试级别的消息。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接