Dmitrij Kultasev
Dmitrij Kultasev

Reputation: 5745

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

I am trying to put trace or exception data to the Application Insights. I am trying the following code:

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

But it does not work, I can not find these traces or exceptions on the Application Insights dashboard, search or metric explorer.

Upvotes: 1

Views: 1025

Answers (4)

Dmitry Matveev
Dmitry Matveev

Reputation: 2679

I think you may want to use InMemoryChannel if you are adding AI into the console/desktop/worker application and would like to Flush synchronously.

InMemoryChannel does not store data locally before it sends telemetry out, so there is no protection from data loss if anything happens on the wire. However, when you call Flush() it will actually try to send the telemetry instead of saving it to the disk.

Using InMemoryChannel will help prevent error-prone code like adding a Sleep() to give some time for ServerTelemetryChannel to send the locally stored telemetry items.

You'll need to replace the ServerTelemetryChannel via code or in the ApplicationInsights.coinfig file:

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

Upvotes: 1

ZakiMa
ZakiMa

Reputation: 6241

It looks like that tc.Flush is not enough. I tried your code in console app and didn't see a request in Fiddler. When added Thread.Sleep(5000) then the exception showed up.

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);
    }
}

And I was able to see an Exception in "Failures" screen.

enter image description here

Upvotes: 2

EranG
EranG

Reputation: 862

I would try adding a 5 seconds sleep before existing the process (after the flush) - IIRC flush only flushes the local buffer, and does not force send the telemetry to Application Insights

Upvotes: 3

Peter
Peter

Reputation: 27934

It takes up to an hour for events/messages are visible in App Insights. I guess you have to be a little more patient for the message to show up.

Upvotes: 0

Related Questions