2
0

ResponseTimeMiddleware.cs 2.9 KB

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