Chr*_*ris 2 .net c# nlog azure azure-application-insights
目标:将日志条目从 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();
Run Code Online (Sandbox Code Playgroud)
使用以下 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>
Run Code Online (Sandbox Code Playgroud)
但是,当 ColoredConsole 目标按预期工作时,没有日志消息到达 Azure Application Insights。消息仅在我调用 时到达TelemetryConfiguration.Active.TelemetryChannel.Flush();。
在客户端将数据发送到门户之前,遥测项目会被缓冲(默认为 30 秒,请参阅源代码)。因此,您必须至少保持控制台打开一段时间或Flush()手动调用或将开发人员模式设置为 true:
TelemetryConfiguration.Active.TelemetryChannel.DeveloperMode = true;
Run Code Online (Sandbox Code Playgroud)
编辑
可以使用多个频道,例如InMemoryChannel或ServerTelemetryChannel。它们都有 30 秒的默认缓冲间隔。
该InMemoryChannel例如有一个公共的属性TimeSpan SendingInterval,所以如果你投的TelemetryConfiguration.Active.TelemetryChannel实际执行情况,你应该能够改变缓冲时间。
请参阅ServerTelemetryChannel.MaxTelemetryBufferDelay和InMemoryChannel.SendingInterval。
| 归档时间: |
|
| 查看次数: |
1092 次 |
| 最近记录: |