jellyfin/Jellyfin.Api/Middleware/ResponseTimeMiddleware.cs

69 lines
2.6 KiB
C#
Raw Normal View History

using System.Diagnostics;
using System.Globalization;
using System.Threading.Tasks;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Controller.Configuration;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
2023-01-31 11:18:10 +00:00
namespace Jellyfin.Api.Middleware;
/// <summary>
/// Response time middleware.
/// </summary>
public class ResponseTimeMiddleware
{
2023-01-31 11:18:10 +00:00
private const string ResponseHeaderResponseTime = "X-Response-Time-ms";
private readonly RequestDelegate _next;
private readonly ILogger<ResponseTimeMiddleware> _logger;
/// <summary>
2023-01-31 11:18:10 +00:00
/// Initializes a new instance of the <see cref="ResponseTimeMiddleware"/> class.
/// </summary>
2023-01-31 11:18:10 +00:00
/// <param name="next">Next request delegate.</param>
/// <param name="logger">Instance of the <see cref="ILogger{ExceptionMiddleware}"/> interface.</param>
public ResponseTimeMiddleware(
RequestDelegate next,
ILogger<ResponseTimeMiddleware> logger)
{
2023-01-31 11:18:10 +00:00
_next = next;
_logger = logger;
}
2023-01-31 11:18:10 +00:00
/// <summary>
/// Invoke request.
/// </summary>
/// <param name="context">Request context.</param>
/// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param>
/// <returns>Task.</returns>
public async Task Invoke(HttpContext context, IServerConfigurationManager serverConfigurationManager)
{
var startTimestamp = Stopwatch.GetTimestamp();
2023-01-31 11:18:10 +00:00
var enableWarning = serverConfigurationManager.Configuration.EnableSlowResponseWarning;
var warningThreshold = serverConfigurationManager.Configuration.SlowResponseThresholdMs;
context.Response.OnStarting(() =>
{
2023-01-31 11:18:10 +00:00
var responseTime = Stopwatch.GetElapsedTime(startTimestamp);
var responseTimeMs = responseTime.TotalMilliseconds;
if (enableWarning && responseTimeMs > warningThreshold && _logger.IsEnabled(LogLevel.Debug))
{
2023-01-31 11:18:10 +00:00
_logger.LogDebug(
2023-02-17 18:27:36 +00:00
"Slow HTTP Response from {Url} to {RemoteIP} in {Elapsed:g} with Status Code {StatusCode}",
2023-01-31 11:18:10 +00:00
context.Request.GetDisplayUrl(),
2023-02-17 18:27:36 +00:00
context.GetNormalizedRemoteIP(),
2023-01-31 11:18:10 +00:00
responseTime,
context.Response.StatusCode);
}
2023-01-31 11:18:10 +00:00
context.Response.Headers[ResponseHeaderResponseTime] = responseTimeMs.ToString(CultureInfo.InvariantCulture);
return Task.CompletedTask;
});
2023-01-31 11:18:10 +00:00
// Call the next delegate/middleware in the pipeline
await this._next(context).ConfigureAwait(false);
}
}