59 lines
1.7 KiB
C#
59 lines
1.7 KiB
C#
using System.Diagnostics;
|
|
|
|
namespace LingAdmin.ApiGateway.Middleware;
|
|
|
|
/// <summary>
|
|
/// 请求日志中间件
|
|
/// </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)
|
|
{
|
|
var stopwatch = Stopwatch.StartNew();
|
|
var requestId = Guid.NewGuid().ToString("N")[..8];
|
|
|
|
// Log request
|
|
_logger.LogInformation(
|
|
"[{RequestId}] {Method} {Path} - Start",
|
|
requestId,
|
|
context.Request.Method,
|
|
context.Request.Path);
|
|
|
|
// Add trace headers
|
|
context.Response.Headers["X-Request-Id"] = requestId;
|
|
context.Response.Headers["X-Correlation-Id"] =
|
|
context.Request.Headers["X-Correlation-Id"].FirstOrDefault() ?? requestId;
|
|
|
|
try
|
|
{
|
|
await _next(context);
|
|
}
|
|
finally
|
|
{
|
|
stopwatch.Stop();
|
|
|
|
var logLevel = context.Response.StatusCode >= 500 ? LogLevel.Error :
|
|
context.Response.StatusCode >= 400 ? LogLevel.Warning :
|
|
LogLevel.Information;
|
|
|
|
_logger.Log(
|
|
logLevel,
|
|
"[{RequestId}] {Method} {Path} - {StatusCode} ({ElapsedMs}ms)",
|
|
requestId,
|
|
context.Request.Method,
|
|
context.Request.Path,
|
|
context.Response.StatusCode,
|
|
stopwatch.ElapsedMilliseconds);
|
|
}
|
|
}
|
|
}
|