Search code examples
c#serilog

Reduce Serilog Excessive Logging on HttpClient Calls


I'm using Serilog in my application for all of my logging needs. When I check my logs, I see excessive logs to the effect of:

[11:58:44 INF] Start processing HTTP request GET [url here]
[11:58:44 INF] Sending HTTP request GET [url here]
[11:58:44 INF] Received HTTP response headers after 148.4156ms - 200
[11:58:44 INF] End processing HTTP request after 164.7209ms - 200

This application makes this particular call very often, so my logs are full of these. When I'm scrolling through for an error log, it makes finding them very hard. So basically I'd like to turn off INFO logs, or at least stop HttpClient calls from logging.

I did find this answer, so I tried adding the following to my appsettings.json:

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

But that didn't have any effect, so I'm wondering if there's additional configuration I have to do.

Here's my logger config setup:

var loggerConfig = new LoggerConfiguration() .WriteTo.Console() .WriteTo.File($"logs/log-{DateTime.Now:dd.MM.yy_HH.mm}.log") .CreateLogger();

and then I just use

services.AddLogging(options => options.AddSerilog(loggerConfig, dispose: true));

to add it. Is there anything else I can do to remove the unwanted logs?


Solution

  • Okay so it looks like I was able to solve this with filters, using this specific configuration:

    var loggerConfig = new LoggerConfiguration()
        .Filter.ByExcluding(logEvent =>
            logEvent.Properties.TryGetValue("SourceContext", out var sourceContext) &&
            sourceContext.ToString().Contains("System.Net.Http.HttpClient") &&
            logEvent.Level == Serilog.Events.LogEventLevel.Information)
        .WriteTo.Console()
        .WriteTo.File($"logs/log-{DateTime.Now:dd.MM.yy_HH.mm}.log")
        .CreateLogger();
    

    This appears to be filtering the Info level logs from System.Net.Http.HttpClient.