Search code examples
c#asp.net-core-mvcasp.net-core-1.0kestrel

Prevent Kestrel from logging errors that are handled in ExceptionFilter


I use an exception filter to log exceptions in my ASP.NET Core app like this:

public void OnException(ExceptionContext context)
{
    var request = context.HttpContext.Request;
    var resource = $"{request?.Method}: {request?.Path}{request?.QueryString}";

    var logger = context.HttpContext.RequestServices.GetService<ILogger<ExceptionFilter>>();
    logger.LogError(0, context.Exception, $"Error in SB.API - {resource}");           
}

This works fine, but Kestrel also logs this event giving me a duplicate entry.

How can I prevent this error from propagating further when I have logged it manually like this?

I do not want to completely turn it off, because then I might miss errors that occur in other parts of the pipeline.


Solution

  • Set context.ExceptionHandled = true; and then Kestrel will know you took care of it and will not log it.