Search code examples
asp.net-web-apiazure-application-insightsglobal-asax.net-4.8

Which Insights implementation guarantees all exceptions get logged?


We have a global.asax.cs file which contains this code...

Approach One

public class WebApiApplication : System.Web.HttpApplication
{
    TelemetryClient _telemetry = new TelemetryClient(new Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration() {
        InstrumentationKey = EnvironmentHelper.InstrumentationKey,
        ConnectionString = EnvironmentHelper.AppInsightsConnectionString
    });

    protected void Application_Start()
    {
        HttpConfiguration config = GlobalConfiguration.Configuration;

        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

I am concerned that this will not log every and all exceptions to Insights. Would it be better to use this code?...

Approach Two

public class WebApiApplication : System.Web.HttpApplication
{
    TelemetryClient _telemetry = new TelemetryClient(...);

    protected void Application_Start()
    {
        HttpConfiguration config = GlobalConfiguration.Configuration;

        config.Filters.Add(new CustomExceptionFilter()); // ADDED LINE

        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

    protected void Application_Error(Object sender, EventArgs e) // ADDED METHOD
    {
        Exception appException = Server.GetLastError();
        _telemetry.TrackException(appException);
    }
}

// ADDED CLASS
public class CustomExceptionFilter : ExceptionFilterAttribute
{
    TelemetryClient _telemetry = new TelemetryClient(...);

    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        _telemetry.TrackException(actionExecutedContext.Exception);
        base.OnException(actionExecutedContext);
    }
}

Are these approaches equal or is one more reliable?


Solution

  • Not sure what do you mean all exceptions get logged.

    Actually, Application Insights will auto collect unhandled exceptions thrown in the controller methods automatically for WebAPI 2+, exception the following scenario:

    • Exceptions thrown from controller constructors.
    • Exceptions thrown from message handlers.
    • Exceptions thrown during routing.
    • Exceptions thrown during response content serialization.
    • Exception thrown during application start-up.
    • Exception thrown in background tasks.

    And For the other exceptions which are handled by application, still need to be tracked manually. You can use the telemetryclient to track these exceptions.

    The referenced doc is here.