diff --git a/api/Sammo.Oeis.Api/Program.cs b/api/Sammo.Oeis.Api/Program.cs index 53b5ab9..a084547 100644 --- a/api/Sammo.Oeis.Api/Program.cs +++ b/api/Sammo.Oeis.Api/Program.cs @@ -41,7 +41,7 @@ services.SetLogFormatter(config.LogFormatter); - services.AddHttpClient(); + services.AddHttpClientWithMinimalLogger(); services.AddWebApi(); diff --git a/api/Sammo.Oeis.Api/Utils.cs b/api/Sammo.Oeis.Api/Utils.cs index 89bd098..a82b8b6 100644 --- a/api/Sammo.Oeis.Api/Utils.cs +++ b/api/Sammo.Oeis.Api/Utils.cs @@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Http.Logging; namespace Sammo.Oeis.Api; @@ -83,6 +84,48 @@ public static IServiceCollection AddWebApi(this IServiceCollection service return services; } + + public static IServiceCollection AddHttpClientWithMinimalLogger(this IServiceCollection services) + where TClient : class where TImplementation : class, TClient + { + services.AddHttpClient() + .RemoveAllLoggers() + .AddLogger(provider => + new MinimalHttpClientLogger(provider.GetRequiredService>())); + + return services; + } + + class MinimalHttpClientLogger : IHttpClientLogger + { + readonly ILogger _logger; + + internal MinimalHttpClientLogger(ILogger logger) + { + _logger = logger; + } + + public object? LogRequestStart(HttpRequestMessage request) => + // client may modify the request URI in the case of redirects, examine the original here + request.RequestUri; + + public void LogRequestStop(object? requestUri, HttpRequestMessage request, HttpResponseMessage response, + TimeSpan elapsed) + { + var numericStatusCode = (int)response.StatusCode; + var logLevel = numericStatusCode < 400 ? LogLevel.Information : LogLevel.Warning; + + _logger.Log(logLevel, "{Method} {Uri} - {StatusCode} ({StatusCodeLiteral}) in {Time}ms", + request.Method, requestUri, numericStatusCode, response.StatusCode, elapsed.TotalMilliseconds); + } + + public void LogRequestFailed(object? requestUri, HttpRequestMessage request, HttpResponseMessage? response, + Exception exception, TimeSpan elapsed) + { + _logger.LogError(exception, "{Method} {Uri} failed in {Time}ms!", + request.Method, requestUri, elapsed.TotalMilliseconds); + } + } } static class EndpointRouteBuilderExtensions