RequestLoggingMilldeware.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using Microsoft.AspNetCore.Connections;
  2. using Microsoft.AspNetCore.Http;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.Diagnostics;
  6. using System.IO;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace FastGithub.HttpServer
  10. {
  11. /// <summary>
  12. /// 请求日志中间件
  13. /// </summary>
  14. sealed class RequestLoggingMiddleware
  15. {
  16. private readonly ILogger<RequestLoggingMiddleware> logger;
  17. /// <summary>
  18. /// 请求日志中间件
  19. /// </summary>
  20. /// <param name="logger"></param>
  21. public RequestLoggingMiddleware(ILogger<RequestLoggingMiddleware> logger)
  22. {
  23. this.logger = logger;
  24. }
  25. /// <summary>
  26. /// 执行请求
  27. /// </summary>
  28. /// <param name="context"></param>
  29. /// <param name="next"></param>
  30. /// <returns></returns>
  31. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  32. {
  33. var stopwatch = Stopwatch.StartNew();
  34. try
  35. {
  36. await next(context);
  37. }
  38. finally
  39. {
  40. stopwatch.Stop();
  41. }
  42. var request = context.Request;
  43. var response = context.Response;
  44. var message = $"{request.Method} {request.Scheme}://{request.Host}{request.Path} responded {response.StatusCode} in {stopwatch.Elapsed.TotalMilliseconds} ms";
  45. var exception = context.GetForwarderErrorFeature()?.Exception;
  46. if (exception == null)
  47. {
  48. this.logger.LogInformation(message);
  49. }
  50. else if (IsError(exception))
  51. {
  52. this.logger.LogError($"{message}{Environment.NewLine}{exception}");
  53. }
  54. else
  55. {
  56. this.logger.LogWarning($"{message}{Environment.NewLine}{GetMessage(exception)}");
  57. }
  58. }
  59. /// <summary>
  60. /// 是否为错误
  61. /// </summary>
  62. /// <param name="exception"></param>
  63. /// <returns></returns>
  64. private static bool IsError(Exception exception)
  65. {
  66. if (exception is OperationCanceledException)
  67. {
  68. return false;
  69. }
  70. if (exception is IOException ioException && ioException.InnerException is ConnectionAbortedException)
  71. {
  72. return false;
  73. }
  74. return true;
  75. }
  76. /// <summary>
  77. /// 获取异常信息
  78. /// </summary>
  79. /// <param name="exception"></param>
  80. /// <returns></returns>
  81. private static string GetMessage(Exception exception)
  82. {
  83. var ex = exception;
  84. var builder = new StringBuilder();
  85. while (ex != null)
  86. {
  87. var type = ex.GetType();
  88. builder.Append(type.Namespace).Append('.').Append(type.Name).Append(": ").AppendLine(ex.Message);
  89. ex = ex.InnerException;
  90. }
  91. return builder.ToString();
  92. }
  93. }
  94. }