Skip to content

Commit

Permalink
[API] Use minimal logging for underlying HTTP api calls
Browse files Browse the repository at this point in the history
  • Loading branch information
burkenyo committed Aug 12, 2024
1 parent c6034da commit 43802e3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
2 changes: 1 addition & 1 deletion api/Sammo.Oeis.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@

services.SetLogFormatter(config.LogFormatter);

services.AddHttpClient<IOeisDecimalExpansionDownloader, OeisDecimalExpansionDownloader>();
services.AddHttpClientWithMinimalLogger<IOeisDecimalExpansionDownloader, OeisDecimalExpansionDownloader>();

services.AddWebApi<ExpansionsApi>();

Expand Down
43 changes: 43 additions & 0 deletions api/Sammo.Oeis.Api/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -83,6 +84,48 @@ public static IServiceCollection AddWebApi<TApi>(this IServiceCollection service

return services;
}

public static IServiceCollection AddHttpClientWithMinimalLogger<TClient, TImplementation>(this IServiceCollection services)
where TClient : class where TImplementation : class, TClient
{
services.AddHttpClient<TClient, TImplementation>()
.RemoveAllLoggers()
.AddLogger(provider =>
new MinimalHttpClientLogger(provider.GetRequiredService<ILogger<TImplementation>>()));

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
Expand Down

0 comments on commit 43802e3

Please sign in to comment.