RequestLoggingMilldeware.cs 3.2 KB

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