c# - 如何在控制台应用程序中退出时执行 "flush"ApplicationInsightsTraceListener?

标签 c# .net azure console-application azure-application-insights

我有一个较旧的控制台应用程序,我正在尝试将跟踪切换为使用 ApplicationInsightsTraceListener 来使用 Application Insights。

如果没有在末尾添加任意 sleep ,我无法获取日志的尾部。

我重新创建了一个非常简单的控制台应用程序,如下所示:

    static void Main(string[] args)
    {
        Trace.TraceInformation("Hello World!");
        Thread.Sleep(10000);
    }

使用Sleep我可以看到它,没有它我就看不到。

我尝试了几种不同的变化来代替 sleep ,例如

        System.Diagnostics.Trace.Flush();

        Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.TelemetryChannel.Flush();

我正在使用开箱即用的 ApplicationInsights.config(我的 Instrumentation Key 除外)。

这是packages.config:

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.ApplicationInsights" version="2.8.1" targetFramework="net472" />
  <package id="Microsoft.ApplicationInsights.Agent.Intercept" version="2.4.0" targetFramework="net472" />
  <package id="Microsoft.ApplicationInsights.DependencyCollector" version="2.8.1" targetFramework="net472" />
  <package id="Microsoft.ApplicationInsights.PerfCounterCollector" version="2.8.1" targetFramework="net472" />
  <package id="Microsoft.ApplicationInsights.TraceListener" version="2.8.1" targetFramework="net472" />
  <package id="Microsoft.ApplicationInsights.WindowsServer" version="2.8.1" targetFramework="net472" />
  <package id="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel" version="2.8.1" targetFramework="net472" />
  <package id="System.Diagnostics.DiagnosticSource" version="4.5.0" targetFramework="net472" />
</packages>

更新

通过以这样的代码块结束,我提高了交付的可靠性,但我仍然不喜欢 sleep 。就此而言,我不喜欢需要修改新跟踪监听器的代码,但我怀疑我是否能摆脱这种情况。

var channel = Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.Active.TelemetryChannel as ServerTelemetryChannel;
channel.MaxTelemetryBufferDelay = TimeSpan.FromSeconds(.5);
Thread.Sleep(channel.MaxTelemetryBufferDelay);

最佳答案

不幸的是,目前没有好的解决方案。仅在所有数据持久化后才返回的 Flush 请求位于 backlog 中.

一种选择是用 InMemoryChannel 替换遥测 channel 。然后Flush将保证数据发送到端点。但如果端点不可用,此 channel 不会重试,因此仍有可能丢失数据。

另一个选择是建立自己的遥测 channel 。但这可能需要大量工作才能使其可靠。

当控制台应用程序返回时,ServerTelemetryChannel 将重新发送数据。但不确定它是否对您的场景有帮助。

关于c# - 如何在控制台应用程序中退出时执行 "flush"ApplicationInsightsTraceListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53768107/

相关文章:

azure - 特定 Azure Web 角色实例的 URL

Azure SQL Serverless 层永远不会关闭

c# - 如何检查集合中的项目是否包含特定值?

c# - 从使用 configSource 文件的 Web.Config 读取值

c# - try/catch block 内的 Response.Redirect 异常

c# - 本地化 WPF 应用程序不起作用?

azure - VPN 证书在一台计算机上始终声明 "This certificate has an invalid digital signature."

c# - 似乎是 .dll 权限 C# 的问题

c# - 有 "Not enough command line parameters exception"吗?

c# - 从 Excel 单元格中的超链接文本中提取 URL