RequestResponseLogging.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. using Aip.Api.Service.Models.Request;
  2. using Aip.Api.Service.Models.Response;
  3. using Aip.Api.Service.Repositories;
  4. using Aip.Api.Service.Services.Interfaces;
  5. using Aip.Api.Service.Utils;
  6. using System.Diagnostics;
  7. namespace Aip.Api.Service.Middlewares;
  8. public class RequestResponseLogging
  9. {
  10. private readonly ILogger<RequestResponseLogging> _log;
  11. private readonly RequestDelegate _next;
  12. public RequestResponseLogging(ILogger<RequestResponseLogging> log, RequestDelegate next)
  13. {
  14. _next = next ?? throw new ArgumentNullException(nameof(next));
  15. _log = log;
  16. _next = next;
  17. }
  18. public async Task Invoke(HttpContext httpContext, IAipDbLoggingService aipDbLoggingService)
  19. {
  20. if (httpContext == null) throw new ArgumentNullException(nameof(httpContext));
  21. string requestUrl = httpContext.Request.Path;
  22. string? remoteIpAddr = httpContext.Connection.RemoteIpAddress?.ToString();
  23. try
  24. {
  25. if (!requestUrl.Contains(GlobalConstants.API_PREFIX))
  26. {
  27. await _next(httpContext);
  28. }
  29. else
  30. {
  31. string fileExt = "";
  32. string dispName = "";
  33. long fileSize = 0;
  34. var start = Stopwatch.GetTimestamp();
  35. string guid = Guid.NewGuid().ToString();
  36. #if false
  37. ApiCallLog apiLog = new ApiCallLog
  38. {
  39. ApiGuid = guid,
  40. RequestAt = DateTime.Now,
  41. ApiEndPoint = httpContext.Request.Path,
  42. IPAddress = httpContext.Connection.RemoteIpAddress?.ToString(),
  43. ErrorMessage = "",
  44. };
  45. #endif
  46. httpContext.Items[GlobalConstants.API_GUID] = guid;
  47. httpContext.Items[GlobalConstants.API_START_TM] = DateTime.Now;
  48. await _next(httpContext);
  49. var statusCode = httpContext.Response.StatusCode;
  50. #if false
  51. apiLog.ResponseStatusCode = statusCode;
  52. apiLog.ErrorCode = GlobalConstants.getAttributeInt(httpContext, GlobalConstants.API_RESULT_CODE);
  53. apiLog.ErrorMessage = GlobalConstants.getAttributeStr(httpContext, GlobalConstants.API_RESULT_MESSAGE);
  54. apiLog.ResponseAt = DateTime.Now;
  55. TimeSpan timeDiff = apiLog.ResponseAt - apiLog.RequestAt;
  56. apiLog.ResponseTime = timeDiff.Milliseconds;
  57. apiLog.TimeStamp = DateTime.Now;
  58. aipDbLoggingService.Send(apiLog);
  59. #endif
  60. if (httpContext.Request.Method != HttpMethod.Post.ToString())
  61. {
  62. return;
  63. }
  64. int apiId = GlobalConstants.GetApiId(httpContext);
  65. if ((apiId >= GlobalConstants.API_FILE_INFO && apiId <= GlobalConstants.API_FILE_DELETE_LABEL_PROTECTION) ||
  66. (apiId >= GlobalConstants.API_STREAM_INFO && apiId <= GlobalConstants.API_STREAM_DELETE_LABEL_PROTECTION))
  67. {
  68. #if false
  69. FileJobLog fileJobLog = new FileJobLog
  70. {
  71. FileId = guid,
  72. FileName = "",
  73. FileExt = "",
  74. FileOwner = "",
  75. FileLabelGuid = "",
  76. FileProtectionGuid = "",
  77. FileSize = 0,
  78. NewFileName = string.Empty,
  79. NewFileExt = string.Empty,
  80. NewFileOwner = string.Empty,
  81. NewFileLabelGuid = string.Empty,
  82. NewFileProtectionGuid = string.Empty,
  83. NewFileSize = 0,
  84. ApiGuid = guid,
  85. ApiId = apiId,
  86. ServerIpAddr = remoteIpAddr,
  87. JobOwner = string.Empty,
  88. ApiKey = string.Empty,
  89. DecryptKey = string.Empty,
  90. JobResult = 0,
  91. JobMessage = string.Empty,
  92. JobTime = apiLog.ResponseTime,
  93. };
  94. if (httpContext.Items[GlobalConstants.API_REQUEST] is RequestBase req)
  95. {
  96. fileJobLog.ApiKey = req.apiKey;
  97. fileJobLog.DecryptKey = req.decryptKey;
  98. fileJobLog.JobOwner = req.email;
  99. }
  100. if (httpContext.Items[GlobalConstants.API_RESULT] is ResponseBase res)
  101. {
  102. dispName = res.dispFileName;
  103. fileJobLog.JobResult = res.errorCode;
  104. fileJobLog.JobMessage = res.errorMessage;
  105. fileJobLog.FileName = res.dispFileName;
  106. fileJobLog.FileOwner = res.FileOwner;
  107. fileJobLog.FileExt = Path.GetExtension(res.dispFileName);
  108. fileJobLog.FileSize = res.FileSize;
  109. fileJobLog.FileLabelGuid = res.FileLabelGuid;
  110. fileJobLog.FileProtectionGuid = res.FileProtectionGuid;
  111. fileJobLog.NewFileName = res.NewFileName;
  112. fileJobLog.NewFileOwner = res.NewFileOwner;
  113. fileJobLog.NewFileExt = Path.GetExtension(res.NewFileName);
  114. fileJobLog.NewFileSize = res.NewFileSize;
  115. fileJobLog.NewFileLabelGuid = res.NewFileLabelGuid;
  116. fileJobLog.NewFileProtectionGuid = res.NewFileProtectionGuid;
  117. }
  118. fileExt = fileJobLog.FileExt;
  119. fileSize = fileJobLog.FileSize;
  120. fileJobLog.TimeStamp = DateTime.Now;
  121. aipDbLoggingService.Send(fileJobLog);
  122. #endif
  123. long apiElapsed = TimeUtils.GetElapsedMilliseconds(start, Stopwatch.GetTimestamp());
  124. if (httpContext.Items[GlobalConstants.API_START_TM] is DateTime startTime)
  125. {
  126. TimeSpan apiTimeDiff = DateTime.Now - startTime;
  127. if (apiTimeDiff.Milliseconds > apiElapsed)
  128. {
  129. apiElapsed = apiTimeDiff.Milliseconds;
  130. }
  131. }
  132. double fileSizekb = Math.Round((double)(fileSize / 1024), 2);
  133. if (apiElapsed > 1500)
  134. {
  135. _log.LogWarning("API Processing: {0}, {1,6} ms. {2,7} KB. {3,-6}, {4}", requestUrl, apiElapsed.ToString("#,##0"), fileSizekb.ToString("#,###,##0"), fileExt, dispName);
  136. }
  137. else
  138. {
  139. _log.LogInformation("API Processing: {0}, {1,6} ms. {2,7} KB. {3,-6}, {4}", requestUrl, apiElapsed.ToString("#,##0"), fileSizekb.ToString("#,###,##0"), fileExt, dispName);
  140. }
  141. }
  142. }
  143. }
  144. catch (Exception e)
  145. {
  146. _log.LogError($"Invoke Exception: {httpContext.Request.Method}, {httpContext.Request.Path}: Excepton Error: {e}");
  147. throw;
  148. }
  149. }
  150. class BenchmarkToken : IDisposable
  151. {
  152. private readonly Stopwatch _stopwatch;
  153. public BenchmarkToken(Stopwatch stopwatch)
  154. {
  155. _stopwatch = stopwatch;
  156. _stopwatch.Start();
  157. }
  158. public void Dispose() => _stopwatch.Stop();
  159. }
  160. }