2
0

RequestLoggingMilldeware.cs 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  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 message = $"{request.Method} {request.Scheme}://{request.Host}{request.Path} responded {response.StatusCode} in {stopwatch.Elapsed.TotalMilliseconds} ms";
  50. var exception = context.GetForwarderErrorFeature()?.Exception;
  51. if (exception == null)
  52. {
  53. this.logger.LogInformation(message);
  54. }
  55. else if (IsError(exception))
  56. {
  57. this.logger.LogError($"{message}{Environment.NewLine}{exception}");
  58. }
  59. else
  60. {
  61. this.logger.LogWarning($"{message}{Environment.NewLine}{GetMessage(exception)}");
  62. }
  63. }
  64. /// <summary>
  65. /// 是否为错误
  66. /// </summary>
  67. /// <param name="exception"></param>
  68. /// <returns></returns>
  69. private static bool IsError(Exception exception)
  70. {
  71. if (exception is OperationCanceledException)
  72. {
  73. return false;
  74. }
  75. if (HasInnerException<ConnectionAbortedException>(exception))
  76. {
  77. return false;
  78. }
  79. return true;
  80. }
  81. /// <summary>
  82. /// 是否有内部异常异常
  83. /// </summary>
  84. /// <typeparam name="TInnerException"></typeparam>
  85. /// <param name="exception"></param>
  86. /// <returns></returns>
  87. private static bool HasInnerException<TInnerException>(Exception exception) where TInnerException : Exception
  88. {
  89. var inner = exception.InnerException;
  90. while (inner != null)
  91. {
  92. if (inner is TInnerException)
  93. {
  94. return true;
  95. }
  96. inner = inner.InnerException;
  97. }
  98. return false;
  99. }
  100. /// <summary>
  101. /// 获取异常信息
  102. /// </summary>
  103. /// <param name="exception"></param>
  104. /// <returns></returns>
  105. private static string GetMessage(Exception exception)
  106. {
  107. var ex = exception;
  108. var builder = new StringBuilder();
  109. while (ex != null)
  110. {
  111. var type = ex.GetType();
  112. builder.Append(type.Namespace).Append('.').Append(type.Name).Append(": ").AppendLine(ex.Message);
  113. ex = ex.InnerException;
  114. }
  115. return builder.ToString();
  116. }
  117. private class RequestLoggingFeature : IRequestLoggingFeature
  118. {
  119. public bool Enable { get; set; } = true;
  120. }
  121. }
  122. }