C# - Serilog, how to stop asp.net request logging on certain paths

This post describes how to exclude certain log entries based on their http path when using Serilog together with UseSerilogRequestLogging. I recently had this issue where all my health checks were logged due to UseSerilogRequestLogging, which caused a ton of unnecessary log events. For this post we will use the following setup:

//More above but not needed for the example
builder.Host.UseSerilog();
var app = builder.Build();
app.UseSerilogRequestLogging();

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateLogger();
//More below but not needed for the example

The above is a simple Serilog setup where we enable request logging and create a simple Logger based on a configuration. While configuring your logger you can set up certain filters and thereby exclude some log events. This we will use to get rid of these request logs. For example if you want to exclude request logging for "/health" you can use the following filter when configuring your logger:

.Filter.ByExcluding(c =>
    {
        if (!c.Properties.ContainsKey("Path"))
            return false;
        return c.Properties["Path"].ToString().StartsWith("/health");
    })

In the above we exclude all paths containing "/health", which is done by looking at the path property of the log event and returning true if it needs to be excluded. The full example would be:

var app = builder.Build();
app.UseSerilogRequestLogging();

Log.Logger = new LoggerConfiguration()
    .Filter.ByExcluding(c =>
    {
        if (!c.Properties.ContainsKey("Path"))
            return false;
        return c.Properties["Path"].ToString().StartsWith("/health");
    })
    .WriteTo.Console()
    .CreateLogger();

That is all there is to it. The combination of request logging and recurring http calls such as health checks or metrics can have unwanted side effects. An alternative to the above is to set the log level, but this will remove all logs on that level - which might be unwanted!

As always please leave a comment down below if this helped you! I will be doing a series on Serilog over the summer.