Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove http client logging handler in ASP.NET Core

When using the HttpClientFactory of .NET Core, is it possible to somehow remove the default LoggingHttpMessageHandler?

I expect something like the below but it doesn't seem to exists

services.AddHttpClient("minos")
   .RemoveHttpMessageHandler<LoggingHttpMessageHandler>();
like image 378
Stephen Lautier Avatar asked Oct 19 '18 09:10

Stephen Lautier


People also ask

What is HttpClient handler?

On the client side, the HttpClient class uses a message handler to process requests. The default handler is HttpClientHandler, which sends the request over the network and gets the response from the server. You can insert custom message handlers into the client pipeline: Note.

What is IHttpClientFactory?

NET Core 2.1 introduced two approaches, one of them being IHttpClientFactory. It's an interface that's used to configure and create HttpClient instances in an app through Dependency Injection (DI). It also provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient.

What is AddHttpClient?

AddHttpClient(IServiceCollection) Adds the IHttpClientFactory and related services to the IServiceCollection. AddHttpClient(IServiceCollection, String) Adds the IHttpClientFactory and related services to the IServiceCollection and configures a named HttpClient.

How do I register IHttpClientFactory in .NET core?

Register an IHttpClientFactory instance in ASP.NET Core You can register an instance of type IHttpClientFactory in the ConfigureServices method of the Startup class by calling the AddHttpClient extension method on the IServiceCollection instance as shown in the code snippet given below.


2 Answers

Just for anyone needing this, I had opened an issue on the GitHub repo, and one of the contributors had replied with the following

services.RemoveAll<IHttpMessageHandlerBuilderFilter>();
  1. Just Add this line AFTER the adding of the HttpClient
  2. Make sure to use Microsoft.Extensions.DependencyInjection.Extensions namespace

https://github.com/aspnet/HttpClientFactory/issues/196#issuecomment-432755765

like image 121
Stephen Lautier Avatar answered Oct 30 '22 13:10

Stephen Lautier


You can configure it in appsettings.json by setting HttpClient's log level to none:

However, this will also enable informational messages from all other components in the System root namespace. Therefore it may be better to configure the logging by limiting the configuration to “System.Net.Http.HttpClient” so that you only add in the messages from the HTTP requests through clients created via the HttpClientFactory:

    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning",
          "System.Net.Http.HttpClient": "Information"
        }
      }
    }

https://www.stevejgordon.co.uk/httpclientfactory-asp-net-core-logging

like image 14
Moien Tajik Avatar answered Oct 30 '22 14:10

Moien Tajik