Skip to content
Robert McLaws edited this page Oct 4, 2015 · 3 revisions

The ApplicationInsights.Helpers.Console package contains two components that help better instrument Console apps. The basis for this code comes from Brandon's DesktopApplicationInsights package, but I've tweaked the design to keep it tightly focused on Console app use cases and naming conventions.

ConsoleContextInitializer

The first one is a ConsoleContextInitializer, which sets some pertinent information about the OS the app is running on every time a new TelemetryClient is created. It has one parameter, an Assembly instance.

Because there is only one constructor, you cannot currently specify this ContextInitializer in the applicationInsights.config file. You have to set it in code, like this:

TelemetryConfiguration.Active.ContextInitializers.Add(new ConsoleContextInitializer(Assembly.GetExecutingAssembly()));

If you're calling this from a library, like we do in ApplicationInsights.Helpers.WebJobs, then use this:

TelemetryConfiguration.Active.ContextInitializers.Add(new ConsoleContextInitializer(Assembly.GetCallingAssembly()));

That way, it gets the details of the assembly that called your library, not your library's assembly.

TelemetryClientExtensions

The TelemetryClientExtensions add a new function to the TelemetryClient, called HandleAppDomainEvents(). This function hooks into AppDomain.UnhandledException and AppDomain.ProcessExit to ensure exception are reported, and that the TelemetryClient is flushed properly before the app exits.

If you're using an IoC container, your code to leverage this functionality would look like this:

builder.Register(context =>
{
    var telemetry = new TelemetryClient();
    telemetry.HandleAppDomainEvents();
    return telemetry;
})
.As<TelemetryClient>()
.SingleInstance();

Otherwise, you can just call that function by itself on any new TelemetryClient instances (but it's a lot easier to use as stated above).

Clone this wiki locally