using HealthMonitor.Common; using Newtonsoft.Json; namespace HealthMonitor.WebApi.Middleware { public class LoggingMiddleware { private readonly RequestDelegate _next; private readonly ILogger _logger; public LoggingMiddleware(RequestDelegate next, ILogger logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { //// 在请求处理之前记录日志 //using (_logger.BeginScope(new Dictionary { ["RequestId"] = "" })) using (new CustomizeStopWatch(nameof(LoggingMiddleware), _logger)) { var request = await FormatRequest(context.Request); _logger.LogInformation(request); var originalBodyStream = context.Response.Body; using var responseBody = new MemoryStream(); context.Response.Body = responseBody; await _next(context); var response = await FormatResponse(context.Response); _logger.LogInformation(response); await responseBody.CopyToAsync(originalBodyStream); } } private async Task FormatRequest(HttpRequest request) { request.EnableBuffering(); var body = await new StreamReader(request.Body).ReadToEndAsync(); var formattedBody = FormatJson(body); request.Body.Position = 0; return $"请求: {request.Scheme} {request.Host}{request.Path} {request.QueryString} {formattedBody}"; } private async Task FormatResponse(HttpResponse response) { response.Body.Seek(0, SeekOrigin.Begin); var body = await new StreamReader(response.Body).ReadToEndAsync(); var formattedBody = FormatJson(body); response.Body.Seek(0, SeekOrigin.Begin); return $"响应: {response.StatusCode}: {formattedBody}"; } private static string FormatJson(string json) { if (string.IsNullOrEmpty(json)) { return string.Empty; } try { var obj = JsonConvert.DeserializeObject(json); // return JsonConvert.SerializeObject(obj, Formatting.Indented); return JsonConvert.SerializeObject(obj); } catch { return json; } } } }