I have an own library that exposes health-check implementation via http client:
In StartupExtensions in my library:
services.AddHttpClient(Consts.HealthChecksHttpClientName, c =>
{
c.BaseAddress = new Uri(options.BaseUrl);
c.DefaultRequestHeaders.Add("Connection", "close");
});
How can I turn off default logging for the health-check url?
I KNOW I can disable all logs:
services.RemoveAll<IHttpMessageHandlerBuilderFilter>();
I don't want to remove all logs from all of http clients that do not belongs to the library - just want to disable only single url for my http client.
Is the way to override for it only for specified HttpClient?
I do not want to use Serilog
- only with standard Microsoft.Extensions.Logging
CodePudding user response:
Your logging filter should be depend on how we make use of HttpClient
. For example, using like this
using var weatherHttpClient = new HttpClient()
// make using here
AFAIK, this case would be impossible to separate logging from HttpClient
.
If we using HttpClient
via DI, we could make a filter like this.
// Register with DI. I'm just a fan of named HttpClient, use your register as wished
services.AddHttpClient(nameof(WeatherService), cfg =>
{
cfg.Timeout = TimeSpan.FromSeconds(10);
cfg.BaseAddress = new Uri("https://api.openweathermap.org");
});
// Using WeatherService class:
private readonly HttpClient _httpClient;
public WeatherService(IHttpClientFactory httpClientFactory)
{
_httpClient = httpClientFactory.CreateClient(nameof(WeatherService));
}
// We can create a logging Filter on Program.cs like
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.AddFilter((_, category, _) => !category.StartsWith($"System.Net.Http.HttpClient.{nameof(WeatherService)}"));
})
Register as services.AddHttpClient<WeatherService>
would result the same category name to filter.
But I still feel it some way cumbersome... of not using Serilog
, could you share the reason why say no to that ?