ResponseTimeMiddleware.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System.Diagnostics;
  2. using System.Globalization;
  3. using System.Threading.Tasks;
  4. using MediaBrowser.Common.Extensions;
  5. using MediaBrowser.Controller.Configuration;
  6. using Microsoft.AspNetCore.Http;
  7. using Microsoft.AspNetCore.Http.Extensions;
  8. using Microsoft.Extensions.Logging;
  9. namespace Jellyfin.Server.Middleware
  10. {
  11. /// <summary>
  12. /// Response time middleware.
  13. /// </summary>
  14. public class ResponseTimeMiddleware
  15. {
  16. private const string ResponseHeaderResponseTime = "X-Response-Time-ms";
  17. private readonly RequestDelegate _next;
  18. private readonly ILogger<ResponseTimeMiddleware> _logger;
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="ResponseTimeMiddleware"/> class.
  21. /// </summary>
  22. /// <param name="next">Next request delegate.</param>
  23. /// <param name="logger">Instance of the <see cref="ILogger{ExceptionMiddleware}"/> interface.</param>
  24. public ResponseTimeMiddleware(
  25. RequestDelegate next,
  26. ILogger<ResponseTimeMiddleware> logger)
  27. {
  28. _next = next;
  29. _logger = logger;
  30. }
  31. /// <summary>
  32. /// Invoke request.
  33. /// </summary>
  34. /// <param name="context">Request context.</param>
  35. /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
  36. /// <returns>Task.</returns>
  37. public async Task Invoke(HttpContext context, IServerConfigurationManager serverConfigurationManager)
  38. {
  39. var watch = new Stopwatch();
  40. watch.Start();
  41. var enableWarning = serverConfigurationManager.Configuration.EnableSlowResponseWarning;
  42. var warningThreshold = serverConfigurationManager.Configuration.SlowResponseThresholdMs;
  43. context.Response.OnStarting(() =>
  44. {
  45. watch.Stop();
  46. if (enableWarning && watch.ElapsedMilliseconds > warningThreshold)
  47. {
  48. _logger.LogWarning(
  49. "Slow HTTP Response from {Url} to {RemoteIp} in {Elapsed:g} with Status Code {StatusCode}",
  50. context.Request.GetDisplayUrl(),
  51. context.GetNormalizedRemoteIp(),
  52. watch.Elapsed,
  53. context.Response.StatusCode);
  54. }
  55. var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
  56. context.Response.Headers[ResponseHeaderResponseTime] = responseTimeForCompleteRequest.ToString(CultureInfo.InvariantCulture);
  57. return Task.CompletedTask;
  58. });
  59. // Call the next delegate/middleware in the pipeline
  60. await this._next(context).ConfigureAwait(false);
  61. }
  62. }
  63. }