-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRequestLoggingMiddleware.cs
More file actions
57 lines (49 loc) · 1.44 KB
/
Copy pathRequestLoggingMiddleware.cs
File metadata and controls
57 lines (49 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System.Diagnostics;
namespace PulseData.API.Middleware;
/// <summary>
/// Logs all incoming HTTP requests and outgoing responses with timing information.
/// Useful for performance monitoring and debugging.
/// </summary>
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<RequestLoggingMiddleware> _logger;
public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
if (context.Request.Path.StartsWithSegments("/api/health", StringComparison.OrdinalIgnoreCase))
{
await _next(context);
return;
}
var stopwatch = Stopwatch.StartNew();
try
{
_logger.LogInformation(
"{Method} {Path} (Query: {Query})",
context.Request.Method,
context.Request.Path,
context.Request.QueryString);
await _next(context);
stopwatch.Stop();
_logger.LogInformation(
"{StatusCode} {Duration}ms",
context.Response.StatusCode,
stopwatch.ElapsedMilliseconds);
}
catch (Exception ex)
{
stopwatch.Stop();
_logger.LogWarning(ex, "Error {Method} {Path} ({Duration}ms): {Error}",
context.Request.Method,
context.Request.Path,
stopwatch.ElapsedMilliseconds,
ex.Message);
throw;
}
}
}