How to link exceptions to Application Insights logging

If you followed the primer AI posts (here and here), you probably had the same question I did: why doesn’t the exception get tacked onto all this “magic” logging.

AI-linking-exceptions-before

If you click that “Learn how to track exceptions for failed requests” it tells you how to track exceptions using AI.

This article will tell you how to get something more like this:

AI-linking-exceptions-after

The key is to set up a filter to log the exception, which AI will automatically link appropriately (e.g. requests).

The filter class

Add this class somewhere in your project:

    using Microsoft.ApplicationInsights;

    public class ExceptionLoggingFilter : ExceptionFilterAttribute
    {
        private static readonly TelemetryClient Ai;

        static LoggingProvider()
        {
            Ai = new TelemetryClient();
        }

        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="actionExecutedContext">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            Ai.TrackException(ex);
        }
    }

Add the exception logging filter

Now, you’ll just need to add the ExceptionLoggingFilter to your Web API configuration.

WebApiConfig.cs:

public static void Register(HttpConfiguration config)
{
     ...
     config.Filters.Add(new ExceptionLoggingFilter())
     ...
}

That’s it. Quick and easy.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: