RequestResponseLogging.cs 7.4 KB

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