AnKing
AnKing

Reputation: 2184

ASP.NET Core 3.1 HttpClient to log only warnings and errors

I've noticed that my application(service) that supposed to run in a backgraund creates a log of garbage logging information because of HttpClient, like so:

info: System.Net.Http.HttpClient.Default.LogicalHandler[100] Start processing HTTP request POST https://localhost:44317/programmatic/getcontent info: System.Net.Http.HttpClient.Default.ClientHandler[100] Sending HTTP request POST https://localhost:44317/programmatic/getcontent info: System.Net.Http.HttpClient.Default.ClientHandler[101] Received HTTP response after 3027.6345ms - OK info: System.Net.Http.HttpClient.Default.LogicalHandler[101] End processing HTTP request after 3028.2987ms - OK info: System.Net.Http.HttpClient.Default.ClientHandler[101] Received HTTP response after 3052.4709ms - OK info: System.Net.Http.HttpClient.Default.LogicalHandler[101] End processing HTTP request after 3053.467ms - OK

Is there a way to configure it anywhere?

I inject client factory like this:

serviceCollection.AddHttpClient();

And then create a client like this:

HttpClient client = _clientFactory.CreateClient();

Upvotes: 28

Views: 21511

Answers (2)

Mihaimyh
Mihaimyh

Reputation: 1410

You can override log level in appsettings.json by adding, for example, a new row to the Logging object:

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

This will log anything from Warning level and above.

Upvotes: 13

kyleJ
kyleJ

Reputation: 398

You can configure Logging in .NET Core through the Appsettings file. You should find a section in the appsettings.json file along the lines

{
  "Logging": {
    "Debug": {
      "LogLevel": {
        "Default": "Information"
      }
    }
  }
}

You can add an additional Log Level filter to specify the minimum log level required to log.

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

Documentation for Logging with filters in .NET Core can be found here.

Documemtation for Logging with filters in the IHttpClientFactory library can be found here. This documentation also includes examples of log filtering with a named HttpClient.

Upvotes: 24

Related Questions