Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

86 lines
2.5KB

  1. using HealthMonitor.Common;
  2. using Newtonsoft.Json;
  3. namespace HealthMonitor.WebApi.Middleware
  4. {
  5. public class LoggingMiddleware
  6. {
  7. private readonly RequestDelegate _next;
  8. private readonly ILogger<LoggingMiddleware> _logger;
  9. public LoggingMiddleware(RequestDelegate next, ILogger<LoggingMiddleware> logger)
  10. {
  11. _next = next;
  12. _logger = logger;
  13. }
  14. public async Task InvokeAsync(HttpContext context)
  15. {
  16. //// 在请求处理之前记录日志
  17. //using (_logger.BeginScope(new Dictionary<string, object> { ["RequestId"] = "" }))
  18. using (new CustomizeStopWatch(nameof(LoggingMiddleware), _logger))
  19. {
  20. var request = await FormatRequest(context.Request);
  21. _logger.LogInformation(request);
  22. var originalBodyStream = context.Response.Body;
  23. using var responseBody = new MemoryStream();
  24. context.Response.Body = responseBody;
  25. await _next(context);
  26. var response = await FormatResponse(context.Response);
  27. _logger.LogInformation(response);
  28. await responseBody.CopyToAsync(originalBodyStream);
  29. }
  30. }
  31. private async Task<string> FormatRequest(HttpRequest request)
  32. {
  33. request.EnableBuffering();
  34. var body = await new StreamReader(request.Body).ReadToEndAsync();
  35. var formattedBody = FormatJson(body);
  36. request.Body.Position = 0;
  37. return $"请求: {request.Scheme} {request.Host}{request.Path} {request.QueryString} {formattedBody}";
  38. }
  39. private async Task<string> FormatResponse(HttpResponse response)
  40. {
  41. response.Body.Seek(0, SeekOrigin.Begin);
  42. var body = await new StreamReader(response.Body).ReadToEndAsync();
  43. var formattedBody = FormatJson(body);
  44. response.Body.Seek(0, SeekOrigin.Begin);
  45. return $"响应: {response.StatusCode}: {formattedBody}";
  46. }
  47. private static string FormatJson(string json)
  48. {
  49. if (string.IsNullOrEmpty(json))
  50. {
  51. return string.Empty;
  52. }
  53. try
  54. {
  55. var obj = JsonConvert.DeserializeObject(json);
  56. // return JsonConvert.SerializeObject(obj, Formatting.Indented);
  57. return JsonConvert.SerializeObject(obj);
  58. }
  59. catch
  60. {
  61. return json;
  62. }
  63. }
  64. }
  65. }