如何从控制台 C# 应用程序获取 trace/exception 数据到 Application Insights

How to get trace/exception data from Console C# application to the Application Insights

我正在尝试将跟踪或异常数据放入 Application Insights。我正在尝试以下代码:

TelemetryClient tc = new TelemetryClient();
tc.InstrumentationKey = "xxxxxx-xxxxxxx-xxxxxxxx-xxxxxxx";
var traceTelemetry = new TraceTelemetry("Console trace critical", SeverityLevel.Critical);
tc.TrackTrace(traceTelemetry);
tc.TrackException(new ApplicationException("Test for AI"));
tc.Flush();

但它不起作用,我无法在 Application Insights 仪表板、搜索或指标资源管理器中找到此类跟踪或异常。

events/messages最多需要一个小时才能在 App Insights 中可见。我想您必须再耐心一点才能看到消息。

我会尝试在现有进程之前(刷新之后)添加 5 秒的睡眠 - IIRC 刷新仅刷新本地缓冲区,不会强制将遥测数据发送到 Application Insights

看来tc.Flush还不够。我在控制台应用程序中尝试了您的代码,但没有在 Fiddler 中看到请求。添加 Thread.Sleep(5000) 时出现异常。

class Program
{
    static void Main(string[] args)
    {
        TelemetryClient tc = new TelemetryClient();
        tc.InstrumentationKey = "fe549116-0099-49fe-a3d6-f36b3dd20860";
        var traceTelemetry = new TraceTelemetry("Console trace critical", SeverityLevel.Critical);
        tc.TrackTrace(traceTelemetry);
        tc.TrackException(new ApplicationException("Test for AI"));
        tc.Flush();

        // Without this line Fiddler didn't show a request
        Thread.Sleep(5000);
    }
}

而且我能够在 "Failures" 屏幕中看到异常。

如果您要将 AI 添加到 console/desktop/worker 应用程序中并且想要 Flush synchronously.

,我认为您可能想要使用 InMemoryChannel

InMemoryChannel 在发送遥测之前不会在本地存储数据,因此如果网络上发生任何事情,则无法防止数据丢失。但是,当您调用 Flush() 时,它实际上会尝试发送遥测数据而不是将其保存到磁盘。

使用 InMemoryChannel 将有助于防止容易出错的代码,例如添加 Sleep() 以便 ServerTelemetryChannel 有时间发送本地存储的遥测项目。

您需要通过代码或在 ApplicationInsights.coinfig 文件中替换 ServerTelemetryChannel

<TelemetryChannel Type="Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.ServerTelemetryChannel, Microsoft.AI.ServerTelemetryChannel">