StackOverthrow
StackOverthrow

Reputation: 1284

Prevent Serilog from writing HTTP events by default

I'm injecting typed HTTP clients in a .NET Core app. I'm also logging with Serilog. I have not intentionally configured any logging of HTTP activity. It magically came with. How do I turn this off?

[12:00:52 INF] Start processing HTTP request POST https://foo/bar
[12:00:52 INF] Sending HTTP request POST https://foo/bar
[12:00:53 INF] Received HTTP response after 707.8906ms - OK

My HTTP client configuration:

services.AddHttpClient("FOO")
    .ConfigureHttpClient(client =>
        {
            client.BaseAddress = new Uri("https://foo/");
        })
    .ConfigurePrimaryHttpMessageHandler(sp => new HttpClientHandler()
        {
            Credentials = new NetworkCredential("user", "pass"),
            ServerCertificateCustomValidationCallback = (senderC, cert, chain, sslPolicyErrors) => true
        })
    .AddTypedClient<Thing1>()
    .AddTypedClient<Thing2>();

Upvotes: 9

Views: 5594

Answers (3)

Wasim
Wasim

Reputation: 724

This can be achieved by adding the following piece of lines in the app settings as well :

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

Upvotes: 0

gtu
gtu

Reputation: 966

Another option is to add an override for System.Net.Http.HttpClient to appsettings.json: enter image description here

Upvotes: 8

Noah Stahl
Noah Stahl

Reputation: 7613

I ran into this and was able to address using Serilog's Filter configuration. Not sure where documented (this appears to be related), but one avenue is to implement the ILogEventFilter interface (source). Include logic for allowing an event, and plug into configuration.

Example filter class:

public class MyLoggingFilter : ILogEventFilter
{
    private static readonly HashSet<string> ignoredMessages = new HashSet<string>(StringComparer.Ordinal)
    {
        "Start processing HTTP request {HttpMethod} {Uri}",
        "End processing HTTP request after {ElapsedMilliseconds}ms - {StatusCode}"
    };

    // Allow the event to be logged if the message template isn't one we ignore
    public bool IsEnabled(LogEvent logEvent) => !ignoredMessages.Contains(logEvent.MessageTemplate.Text);
}

Added to configuration (Program.cs in this case):

config
    .MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
    .Enrich.FromLogContext()
    .Filter.With<MyLoggingFilter>() // <-- Plug in your filter type
    .WriteTo.Console(theme: AnsiConsoleTheme.Code)
    .WriteTo.Debug()
    // etc

Alternatively, if you want to prevent any logging related to HttpClient, override the category (which is the type namespace) with desired log level:

config.MinimumLevel.Override("System.Net.Http.HttpClient", LogEventLevel.Warning) 

Upvotes: 9

Related Questions