How to use IHttpClientAsyncLogger for logging http request/response details?

57 Views Asked by At

In My Worker application, I need to log all outgoing requests and incoming responses. I found that there is an IHttpClientAsyncLogger that can add logging functionality in desired httpclient. So, I implemented the IHttpClientAsyncLogger interface like this:

public class HttpClientLogger : IHttpClientAsyncLogger
{
    private readonly ILogger<HttpClientLogger> _logger;
    public HttpClientLogger(ILogger<HttpClientLogger> logger)
    {
        _logger = logger;
        _logger.LogInformation("httpclient logger initiated");
    }
    public object? LogRequestStart(HttpRequestMessage request)
    {
        _logger.LogInformation("My logger hit on : {function}", nameof(LogRequestStart));
        return request;
    }

    public void LogRequestStop(object? context, HttpRequestMessage request, HttpResponseMessage response, TimeSpan elapsed)
    {
        _logger.LogInformation("My logger hit on : {function}", nameof(LogRequestStop));
    }

    public void LogRequestFailed(object? context, HttpRequestMessage request, HttpResponseMessage? response, Exception exception,
        TimeSpan elapsed)
    {
        _logger.LogInformation("My logger hit on : {function}", nameof(LogRequestFailedAsync));
    }

    public ValueTask<object?> LogRequestStartAsync(HttpRequestMessage request,
        CancellationToken cancellationToken = new CancellationToken())
    {
        _logger.LogInformation("My logger hit on : {function}", nameof(LogRequestStartAsync));
        return ValueTask.FromResult<object?>(request);
    }

    public ValueTask LogRequestStopAsync(object? context, HttpRequestMessage request, HttpResponseMessage response,
        TimeSpan elapsed, CancellationToken cancellationToken = new CancellationToken())
    {
        _logger.LogInformation("My logger hit on : {function}", nameof(LogRequestStopAsync));
        return ValueTask.CompletedTask;
    }

    public ValueTask LogRequestFailedAsync(object? context, HttpRequestMessage request, HttpResponseMessage? response,
        Exception exception, TimeSpan elapsed, CancellationToken cancellationToken = new CancellationToken())
    {
        _logger.LogInformation("My logger hit on : {function}", nameof(LogRequestFailedAsync));
        return ValueTask.CompletedTask;
    }
}

and then register it as below in my service collection in program.cs:

Host.CreateDefaultBuilder(args)
    .ConfigureLogging((context, loggingBuilder) =>
    {
        var logger = new LoggerConfiguration()
            .ReadFrom.Configuration(context.Configuration).CreateLogger();
        loggingBuilder.AddSerilog(logger);
    })
    .ConfigureServices(services =>
    {
 services.AddHttpClient("MyHttpClient", client =>
            {
                client.Timeout = TimeSpan.FromSeconds(150);
            }).RemoveAllLoggers()
            .AddLogger<HttpClientLogger>().AddPolicyHandler(GetRetryPolicy());
};

but when my client composes the HTTP request and receives the response none of the logging methods will be called.

How should I use the HTTP client logging infrastructure?

Update:

I Checked the "System.Net.Http.HttpClient" logging filter and also Implementing the IHttpClientLogger but no change in the final result.

Also, it is useful to mention that according to this documentation the sync methods are called in sync Send method of the HttpMessageHandler and async methods are called by SendAsync method.

1

There are 1 best solutions below

0
Navid_pdp11 On

I found the answer. It was my mistake that I was registering my HttpClientFactory using this code:

services.AddHttpClient("MyHttpClient", client =>
            {
                client.Timeout = TimeSpan.FromSeconds(150);
            }).RemoveAllLoggers()
            .AddLogger<HttpClientLogger>().AddPolicyHandler(GetRetryPolicy());

but I was instantiating my HttpClient using this code:

var client = ClientFactory.CreateClient("MyClient");