RequestLoggingMilldeware.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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.Text;
  7. using System.Threading.Tasks;
  8. namespace FastGithub.HttpServer
  9. {
  10. /// <summary>
  11. /// 请求日志中间件
  12. /// </summary>
  13. sealed class RequestLoggingMiddleware
  14. {
  15. private readonly ILogger<RequestLoggingMiddleware> logger;
  16. /// <summary>
  17. /// 请求日志中间件
  18. /// </summary>
  19. /// <param name="logger"></param>
  20. public RequestLoggingMiddleware(ILogger<RequestLoggingMiddleware> logger)
  21. {
  22. this.logger = logger;
  23. }
  24. /// <summary>
  25. /// 执行请求
  26. /// </summary>
  27. /// <param name="context"></param>
  28. /// <param name="next"></param>
  29. /// <returns></returns>
  30. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  31. {
  32. var feature = new RequestLoggingFeature();
  33. context.Features.Set<IRequestLoggingFeature>(feature);
  34. var stopwatch = Stopwatch.StartNew();
  35. try
  36. {
  37. await next(context);
  38. }
  39. finally
  40. {
  41. stopwatch.Stop();
  42. }
  43. if (feature.Enable == false)
  44. {
  45. return;
  46. }
  47. var request = context.Request;
  48. var response = context.Response;
  49. var exception = context.GetForwarderErrorFeature()?.Exception;
  50. if (exception == null)
  51. {
  52. this.logger.LogInformation($"{request.Method} {request.Scheme}://{request.Host}{request.Path} responded {response.StatusCode} in {stopwatch.Elapsed.TotalMilliseconds} ms");
  53. }
  54. else if (IsError(exception))
  55. {
  56. this.logger.LogError($"{request.Method} {request.Scheme}://{request.Host}{request.Path} responded {response.StatusCode} in {stopwatch.Elapsed.TotalMilliseconds} ms{Environment.NewLine}{exception}");
  57. }
  58. else
  59. {
  60. this.logger.LogWarning($"{request.Method} {request.Scheme}://{request.Host}{request.Path} responded {response.StatusCode} in {stopwatch.Elapsed.TotalMilliseconds} ms{Environment.NewLine}{GetMessage(exception)}");
  61. }
  62. }
  63. /// <summary>
  64. /// 是否为错误
  65. /// </summary>
  66. /// <param name="exception"></param>
  67. /// <returns></returns>
  68. private static bool IsError(Exception exception)
  69. {
  70. if (exception is OperationCanceledException)
  71. {
  72. return false;
  73. }
  74. if (HasInnerException<ConnectionAbortedException>(exception))
  75. {
  76. return false;
  77. }
  78. return true;
  79. }
  80. /// <summary>
  81. /// 是否有内部异常异常
  82. /// </summary>
  83. /// <typeparam name="TInnerException"></typeparam>
  84. /// <param name="exception"></param>
  85. /// <returns></returns>
  86. private static bool HasInnerException<TInnerException>(Exception exception) where TInnerException : Exception
  87. {
  88. var inner = exception.InnerException;
  89. while (inner != null)
  90. {
  91. if (inner is TInnerException)
  92. {
  93. return true;
  94. }
  95. inner = inner.InnerException;
  96. }
  97. return false;
  98. }
  99. /// <summary>
  100. /// 获取异常信息
  101. /// </summary>
  102. /// <param name="exception"></param>
  103. /// <returns></returns>
  104. private static string GetMessage(Exception exception)
  105. {
  106. var ex = exception;
  107. var builder = new StringBuilder();
  108. while (ex != null)
  109. {
  110. var type = ex.GetType();
  111. builder.Append(type.Namespace).Append('.').Append(type.Name).Append(": ").AppendLine(ex.Message);
  112. ex = ex.InnerException;
  113. }
  114. return builder.ToString();
  115. }
  116. private class RequestLoggingFeature : IRequestLoggingFeature
  117. {
  118. public bool Enable { get; set; } = true;
  119. }
  120. }
  121. }