Search code examples
c#.net-coreloggingdotnet-httpclient

HttpClient logging sensitive data


Is it possible to disable logging headers of requests/responses performed using HttpClient at every log level?

Registering custom HttpClient into DI like this:

services.AddHttpClient<CustomHttpClient>(config =>
{
    config.BaseAddress = new Uri(CustomBaseAddress);
    config.DefaultRequestHeaders.Authorization = new(AuthorizationKey, AuthorizationValue);
});

After request is performed logs are looking like this:

info: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
      Start processing HTTP request GET {CustomBaseAddress}
trce: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
      Request Headers:
      Authorization: {AuthorizationKey} {AuthorizationValue}

I know I can set min log level in app configuration for System.Net.Http.HttpClient.CustomHttpClient to none (or something higher that trace). But I want to avoid doing that.

So is there a way how to configure HttpClient to not logging headers?


Solution

  • I finally ended up with pretty easy solution. And its by using extension method HttpClientBuilderExtensions.RedactLoggedHeaders

    Example:

    services.AddHttpClient<CustomHttpClient>(config =>
    {
        config.BaseAddress = new Uri(CustomBaseAddress);
        config.DefaultRequestHeaders.Authorization = new(AuthorizationKey, AuthorizationValue);
    })
    .RedactLoggedHeaders(new string[] { "Authorization" });
    

    This method hides headers values before logging.

    from this:

    trce: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
          Request Headers:
          Authorization: {AuthorizationKey} {AuthorizationValue}
    

    to this:

    trce: System.Net.Http.HttpClient.CustomHttpClient.LogicalHandler
          Request Headers:
          Authorization: *