-
-
Save nblumhardt/a9a5dbf4e9ae2e4234d5d501baf5f764 to your computer and use it in GitHub Desktop.
Example request logging middleware for ASP.NET Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Diagnostics; | |
namespace GettingStarted; | |
class RequestLoggingMiddleware | |
{ | |
readonly RequestDelegate _next; | |
readonly ILogger _logger; | |
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger) | |
{ | |
_next = next ?? throw new ArgumentNullException(nameof(next)); | |
_logger = logger ?? throw new ArgumentNullException(nameof(logger)); | |
} | |
public async Task Invoke(HttpContext httpContext) | |
{ | |
if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); | |
var start = Stopwatch.GetTimestamp(); | |
try | |
{ | |
await _next(httpContext); | |
var elapsed = Stopwatch.GetElapsedTime(start, Stopwatch.GetTimestamp()); | |
var statusCode = httpContext.Response.StatusCode; | |
LogCompletion(httpContext, statusCode, elapsed, null); | |
} | |
catch (Exception ex) when (LogCompletion(httpContext, 500, Stopwatch.GetElapsedTime(start, Stopwatch.GetTimestamp()), ex)) | |
{ | |
} | |
} | |
bool LogCompletion(HttpContext httpContext, int statusCode, TimeSpan elapsed, Exception? exception) | |
{ | |
var level = exception != null | |
? LogLevel.Error | |
: statusCode > 499 | |
? LogLevel.Error | |
: LogLevel.Information; | |
_logger.Log( | |
level, | |
default, | |
exception, | |
"HTTP {RequestMethod} {RequestPath} responded {StatusCode} in {Elapsed:0.0000} ms", | |
httpContext.Request.Method, | |
httpContext.Request.Path, | |
statusCode, | |
elapsed.TotalMilliseconds); | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment