RequestLoggingMilldeware.cs 1.6 KB

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