PerformaceMonitorMiddleware.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.Extensions.Logging;
  3. using System.Diagnostics;
  4. using System.Threading.Tasks;
  5. namespace EVCB_OCPP.WEBAPI.Middleware;
  6. public class PerformaceMonitorMiddlewareOptions
  7. {
  8. public string Label { get; set; }
  9. }
  10. public class PerformaceMonitorMiddleware
  11. {
  12. private readonly RequestDelegate _next;
  13. private readonly PerformaceMonitorMiddlewareOptions options;
  14. private readonly ILogger<PerformaceMonitorMiddleware> logger;
  15. public PerformaceMonitorMiddleware(
  16. RequestDelegate next,
  17. PerformaceMonitorMiddlewareOptions options,
  18. ILogger<PerformaceMonitorMiddleware> logger)
  19. {
  20. _next = next;
  21. this.options = options;
  22. this.logger = logger;
  23. }
  24. public async Task Invoke(HttpContext context)
  25. {
  26. var timer = Stopwatch.StartNew();
  27. await _next(context);
  28. timer.Stop();
  29. if (timer.ElapsedMilliseconds / 1000 > 1)
  30. {
  31. logger.LogCritical("{0} {1} {2} cost {3}", options.Label, context.Request.Method, context.Request.Path, timer.ElapsedMilliseconds);
  32. }
  33. }
  34. }