Skip to content

Instantly share code, notes, and snippets.

@nblumhardt
Created June 13, 2023 04:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nblumhardt/a9a5dbf4e9ae2e4234d5d501baf5f764 to your computer and use it in GitHub Desktop.
Save nblumhardt/a9a5dbf4e9ae2e4234d5d501baf5f764 to your computer and use it in GitHub Desktop.
Example request logging middleware for ASP.NET Core
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