Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent HttpClient via IHttpClientFactory from logging to ILogger?

I am writing a custom ILoggerProvider which forwards log messages over HTTP using an HttpClient instance obtained via the configured IHttpClientFactory:

public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpClient();
}

When my ILoggerProvider forwards a batch of logs, its HttpClient generates additional log messages, which then get forwarded... resulting in a stack overflow of sorts.

How can I suppress only the messages that are generated within the limited scope of the method that performs the forwarding, so that I can filter out logs from HttpClient or anything else that might be logging during that scope?

like image 654
JoeGaggler Avatar asked Dec 27 '25 23:12

JoeGaggler


2 Answers

I am writing a custom ILoggerProvider which forwards log messages over HTTP using an HttpClient instance obtained via the configured IHttpClientFactory:

Just don't do that, use another HttpClient that isn't tied to the factory.

like image 77
davidfowl Avatar answered Dec 30 '25 13:12

davidfowl


Named instances of HttpClient created via IHttpClientFactory use log categories containing those names. Logs sent to this forwarding provider can then be filtered out.

If a named HttpClient is created like this:

httpClientFactory.CreateClient(nameof(MyForwardingLoggerProvider))))

Then one possible way to filter out the logs is to return a "no-op" instance when this HttpClient instance attempts to create an ILogger with the provider name in the categoryName:

ILogger ILoggerProvider.CreateLogger(String categoryName)
{
    if (categoryName.StartsWith($"System.Net.Http.HttpClient.{nameof(MyForwardingLoggerProvider)}."))
    {
        // Ignores all logs
        return NoopLogger.Instance;
    }
    else
    {
        // Performs log forwarding
        return new MyForwardingLogger(categoryName);
    }
}
like image 37
JoeGaggler Avatar answered Dec 30 '25 12:12

JoeGaggler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!