How to clear the exception to prevent being logged twice by Application Insights
Mykhailo Kostiuchenko
1
Reputation point
I installed Application Insights into my ASP.NET Web API application. I added global exception handler to log specific exception as a custom events to App Insights:
public class AppExceptionHandler : ExceptionHandler
{
private readonly IAuthEventLogger _authEventLogger;
public AppExceptionHandler()
{
_authEventLogger = DependencyResolver.Current.GetService<IAuthEventLogger>();
}
public override void Handle(ExceptionHandlerContext context)
{
Exception ex = context.Exception;
IHttpActionResult newResult = null;
while (ex != null)
{
if (ex is AppSessionException)
{
newResult = new StatusCodeResult(HttpStatusCode.Unauthorized, context.Request);
_authEventLogger.TrackUnauthorizedRequestEvent(context.Request.RequestUri.PathAndQuery);
break;
}
}
if (newResult != null)
{
context.Result = newResult;
}
else
{
base.Handle(context);
}
}
}
It works fine, But now all the exceptions are logged twice: in addition to custom events that my logger writes to, exceptions are also logged automatically in the "Failures" App Insights section.
Is there a way to not log automatically my custom exceptions as "Failures" and log all others?
Sign in to answer