PerformanceBehaviour.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.Extensions.Logging;
  3. using System.Diagnostics;
  4. namespace AipGateway.API.Application.Pipeline.Middlewares.Behaviours
  5. {
  6. public class PerformanceBehaviour
  7. {
  8. private readonly Stopwatch _timer;
  9. private readonly ILogger<HttpRequest> _log;
  10. //private readonly ICurrentUserService _currentUserService;
  11. private readonly RequestDelegate _next;
  12. public PerformanceBehaviour(ILogger<HttpRequest> logger, RequestDelegate next)
  13. {
  14. _timer = new Stopwatch();
  15. //_currentUserService = currentUserService;
  16. _log = logger;
  17. _next = next;
  18. _log.LogError("ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo: PerformanceBehaviour");
  19. }
  20. public async Task InvokeAsync(HttpContext context)
  21. {
  22. try
  23. {
  24. _timer.Start();
  25. //_log.LogError("PerformanceBehaviour Invoke Before:");
  26. await _next.Invoke(context);
  27. _timer.Stop();
  28. //_log.LogError("PerformanceBehaviour Invoke After:");
  29. var elapsedMilliseconds = _timer.ElapsedMilliseconds;
  30. if (elapsedMilliseconds > 500)
  31. {
  32. //var requestName = context.Request.Path;
  33. //var requestedPath = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path} {context.Request.QueryString}".Trim();
  34. //var userName = "Swagger";
  35. //if (!string.IsNullOrEmpty(_currentUserService.Email))
  36. //{
  37. // userName = _currentUserService.Email;
  38. //}
  39. //_log.LogWarning("API Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@RequestedPath} {@UserName}",
  40. // requestName, elapsedMilliseconds, requestedPath, userName);
  41. }
  42. _log.LogError("PerformanceBehaviour.........................................................................");
  43. }
  44. catch (Exception)
  45. {
  46. throw;
  47. }
  48. await Task.FromResult(Task.CompletedTask);
  49. return;
  50. }
  51. }
  52. }