使用 Microsoft.ApplicationInsights.NLogTarget 的 Azure Application Insights 中没有日志条目

No log entries in Azure Application Insights using Microsoft.ApplicationInsights.NLogTarget

目标:将日志条目从 NLog 转发到 Azure Application Insights。从: https://github.com/Microsoft/ApplicationInsights-dotnet-logging

我创建了一个非常基本的控制台应用程序:

TelemetryConfiguration.Active.InstrumentationKey = "my instrumentation key";

Logger logger = LogManager.GetLogger("Example");
logger.Info("Hello World");

Console.ReadLine();

与以下 app.config:

<configuration>
  <configSections>
    <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />
  </startup>
  <nlog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true">
    <extensions>
      <add assembly="Microsoft.ApplicationInsights.NLogTarget" />
    </extensions>
    <targets>
      <target type="ApplicationInsightsTarget" name="aiTarget" layout="${longdate} ${level} ${threadid} ${logger} ${message} ${exception:format=ToString}" />
      <target name="console" xsi:type="ColoredConsole" layout="${longdate} ${level} ${threadid} ${logger} ${message} ${exception:format=ToString}" />
    </targets>
    <rules>
      <logger name="*" minlevel="Trace" writeTo="aiTarget" />
      <logger name="*" minlevel="Trace" writeTo="console" />
    </rules>
  </nlog>
</configuration>

但是当 ColoredConsole 目标按预期工作时,没有日志消息到达 Azure Application Insights。消息仅在我调用 TelemetryConfiguration.Active.TelemetryChannel.Flush(); 时到达。

遥测项目被缓冲(默认情况下为 30 秒,请参阅 the source code) before the client send the data to the portal. So you have to keep the console open for at least that amount of time or call Flush() manually or set the developer mode 为真:

TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;

编辑 可以使用多个通道,例如 InMemoryChannelServerTelemetryChannel。它们都具有 30 秒的默认缓冲间隔。

例如 InMemoryChannel 有一个 public 属性 TimeSpan SendingInterval 所以如果你将 TelemetryConfiguration.Active.TelemetryChannel 转换为实际的实现你应该能够改变缓冲间隔。

ServerTelemetryChannel.MaxTelemetryBufferDelay and InMemoryChannel.SendingInterval