RequestLoggingMilldeware.cs 1.9 KB

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