RequestLoggingMilldeware.cs 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  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 stopwatch = Stopwatch.StartNew();
  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 exception = context.GetForwarderErrorFeature()?.Exception;
  45. if (exception == null)
  46. {
  47. this.logger.LogInformation(message);
  48. }
  49. else if (IsError(exception))
  50. {
  51. this.logger.LogError($"{message}{Environment.NewLine}{exception}");
  52. }
  53. else
  54. {
  55. this.logger.LogWarning($"{message}{Environment.NewLine}{GetMessage(exception)}");
  56. }
  57. }
  58. /// <summary>
  59. /// 是否为错误
  60. /// </summary>
  61. /// <param name="exception"></param>
  62. /// <returns></returns>
  63. private static bool IsError(Exception exception)
  64. {
  65. if (exception is OperationCanceledException)
  66. {
  67. return false;
  68. }
  69. if (HasInnerException<ConnectionAbortedException>(exception))
  70. {
  71. return false;
  72. }
  73. return true;
  74. }
  75. /// <summary>
  76. /// 是否有内部异常异常
  77. /// </summary>
  78. /// <typeparam name="TInnerException"></typeparam>
  79. /// <param name="exception"></param>
  80. /// <returns></returns>
  81. private static bool HasInnerException<TInnerException>(Exception exception) where TInnerException : Exception
  82. {
  83. var inner = exception.InnerException;
  84. while (inner != null)
  85. {
  86. if (inner is TInnerException)
  87. {
  88. return true;
  89. }
  90. inner = inner.InnerException;
  91. }
  92. return false;
  93. }
  94. /// <summary>
  95. /// 获取异常信息
  96. /// </summary>
  97. /// <param name="exception"></param>
  98. /// <returns></returns>
  99. private static string GetMessage(Exception exception)
  100. {
  101. var ex = exception;
  102. var builder = new StringBuilder();
  103. while (ex != null)
  104. {
  105. var type = ex.GetType();
  106. builder.Append(type.Namespace).Append('.').Append(type.Name).Append(": ").AppendLine(ex.Message);
  107. ex = ex.InnerException;
  108. }
  109. return builder.ToString();
  110. }
  111. }
  112. }