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?
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With