What is the relation between CustomErrors web.config setting and azure app insights logging?

278 views Asked by At

Link: https://learn.microsoft.com/en-us/azure/azure-monitor/app/asp-net-exceptions#prior-versions-support

If the CustomErrors configuration is Off, then exceptions will be available for the HTTP Module to collect.

//If customError is Off, then AI HTTPModule will report the exception
                if (filterContext.HttpContext.IsCustomErrorEnabled)
                {   //or reuse instance (recommended!). see note above
                    var ai = new TelemetryClient();
                    ai.TrackException(filterContext.Exception);
                }

If IsCustomErrorEnabled then it will track exception. For IsCustomErrorEnabled to be true, customError must be ON. So why does it say - If customError is Off, then AI HTTPModule will report the exception?

1

There are 1 answers

0
Anna Gevel On

I think the comment in this Microsoft example is a bit misleading, here is what it means:

  • If CustomErrors is Off, the Application Insights HTTP module will handle all the exceptions as expected. Application Insights HTTP module should be present in web.config <modules> section
  • If CustomErrors is On, the Application Insights HTTP module will NOT be able to track exceptions, that is why we need a workaround with the custom attribute class

Therefore, the attribute example code uses the statement if (filterContext.HttpContext.IsCustomErrorEnabled) to avoid logging exceptions twice: in the custom attribute and Application Insights HTTP module.

It would be clearer if the comment said something like this:

//The attribute should track exceptions only when CustomErrors setting is On
//if CustomErrors is Off, exceptions will be caught by AI HTTP Module
if (filterContext.HttpContext.IsCustomErrorEnabled)
{
    var ai = new TelemetryClient();
    ai.TrackException(filterContext.Exception);
}

Please note that all of the above is only relevant for MVC 4 and prior versions. Starting from MVC 5, Application Insights can collect unhandled exceptions automatically and no workarounds are required.

UPDATE: I suggested an improvement for this documentation page and it has been approved by the Azure docs team.