RequestLoggingMilldeware.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Threading.Tasks;
  6. namespace FastGithub.ReverseProxy
  7. {
  8. /// <summary>
  9. /// 请求日志中间件
  10. /// </summary>
  11. sealed class RequestLoggingMilldeware
  12. {
  13. private readonly ILogger<RequestLoggingMilldeware> logger;
  14. /// <summary>
  15. /// 请求日志中间件
  16. /// </summary>
  17. /// <param name="logger"></param>
  18. public RequestLoggingMilldeware(ILogger<RequestLoggingMilldeware> logger)
  19. {
  20. this.logger = logger;
  21. }
  22. /// <summary>
  23. /// 执行请求
  24. /// </summary>
  25. /// <param name="context"></param>
  26. /// <param name="next"></param>
  27. /// <returns></returns>
  28. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  29. {
  30. var stopwatch = new Stopwatch();
  31. stopwatch.Start();
  32. try
  33. {
  34. await next(context);
  35. }
  36. finally
  37. {
  38. stopwatch.Stop();
  39. }
  40. var request = context.Request;
  41. var response = context.Response;
  42. var message = $"{request.Method} {request.Scheme}://{request.Host}{request.Path} responded {response.StatusCode} in {stopwatch.Elapsed.TotalMilliseconds} ms";
  43. var exception = context.GetForwarderErrorFeature()?.Exception;
  44. if (exception == null)
  45. {
  46. this.logger.LogInformation(message);
  47. }
  48. else
  49. {
  50. this.logger.LogError($"{message}{Environment.NewLine}{exception.Message}");
  51. }
  52. }
  53. }
  54. }