RequestLoggingMiddleware does not swallow exception
See original GitHub issueI am using AspNetCore with ApplicationInsights and Serilog. In development environment exceptions are logged twice , because RequestLoggingMiddleware is not swallowing exceptions and DeveloperExceptionPageMiddleware is handling the exception and logging it.
Shouldn’t LogCompletion
return true to swallow the exception?
private bool LogCompletion(HttpContext httpContext, DiagnosticContextCollector collector, int statusCode, double elapsedMs, Exception ex) { var level = statusCode > 499 ? LogEventLevel.Error : LogEventLevel.Information; if (!Log.IsEnabled(level)) return false; if (!collector.TryComplete(out var properties)) properties = NoProperties; var logEventProperties = properties.Concat(new[] { new LogEventProperty("RequestMethod", new ScalarValue( httpContext.Request.Method)), new LogEventProperty("RequestPath", new ScalarValue(GetPath(httpContext))), new LogEventProperty("StatusCode", new ScalarValue(statusCode)), new LogEventProperty("Elapsed", new ScalarValue(elapsedMs)) }); Log.Write(new LogEvent(DateTimeOffset.UtcNow, level, ex, _messageTemplate, logEventProperties)); return false; // true?! }
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
The above explanation makes sense to me, but it might be worth noting in the documentation that exceptions will be logged twice when the RequestLoggingMiddleware is enabled. I spent a few hours tracking this down and I am guessing others will too. It might help folks save time if they happen to notice it.
Howdy! There are a couple of things going on 👍
LogCompletion()
returnsbool false
so that it can be used directly in thewhen
clause of the exception handler (the expression there needs to evaluate to a Boolean, and this is the cleanest way to do that).The exception filter is used so that enriched properties are captured at the site where the exception is thrown, rather than where it’s caught - this is one of the “hidden” features of
when
clauses - they are executed at a rather surprising time, which just happens to be convenient for capturing logs.Overall, swallowing the exception isn’t an option in the middleware because we’d prevent custom error handling pipelines like the developer exception page, etc., from being invoked - I did give it a try at one point, but it was unworkable.
HTH!