2025-03-06 04:17:44 +00:00
|
|
|
// Copyright (c) Duende Software. All rights reserved.
|
2025-03-01 18:55:40 +00:00
|
|
|
// See LICENSE in the project root for license information.
|
|
|
|
|
|
|
|
|
|
using System.Diagnostics;
|
2025-01-14 14:59:42 +00:00
|
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
|
|
2025-08-29 20:08:52 +00:00
|
|
|
namespace Duende.Xunit.Playwright;
|
2025-01-14 14:59:42 +00:00
|
|
|
|
|
|
|
|
public class RequestLoggingHandler(
|
|
|
|
|
ILogger<RequestLoggingHandler> log,
|
|
|
|
|
Func<HttpRequestMessage, bool> shouldLog)
|
|
|
|
|
: DelegatingHandler
|
|
|
|
|
{
|
|
|
|
|
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
|
|
|
|
|
CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
if (!shouldLog(request))
|
|
|
|
|
{
|
|
|
|
|
return await base.SendAsync(request, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var stopwatch = Stopwatch.StartNew();
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var result = await base.SendAsync(request, cancellationToken);
|
|
|
|
|
|
|
|
|
|
log.LogInformation("Executing {method} on {url} returned {statuscode} in {ms} ms",
|
|
|
|
|
request.Method,
|
|
|
|
|
request.RequestUri,
|
|
|
|
|
result.StatusCode,
|
|
|
|
|
stopwatch.ElapsedMilliseconds);
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
}
|
|
|
|
|
catch (OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
log.LogWarning("Executing {method} on {url} was cancelled in {ms} ms",
|
|
|
|
|
request.Method,
|
|
|
|
|
request.RequestUri,
|
|
|
|
|
stopwatch.ElapsedMilliseconds);
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
log.LogWarning(ex,
|
|
|
|
|
"Exception while executing {method} on {url} in {ms} ms",
|
|
|
|
|
request.Method,
|
|
|
|
|
request.RequestUri,
|
|
|
|
|
stopwatch.ElapsedMilliseconds);
|
|
|
|
|
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
}
|
2025-03-06 04:26:44 +00:00
|
|
|
}
|