C# - Serilog, how to ignore certain logs based on properties

This post describes how to exclude certain log entries based on properties using Serilog. We will use the following setup for this post:

//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. For example if you want to exclude request logging for swagger 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("/swagger");
    })

In the above we exclude all paths containing "/swagger", 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("/swagger");
    })
    .WriteTo.Console()
    .CreateLogger();

If you are massing the property to exclude on, check out my post on how to enrich serilog log events with more properties!

That is all

That is all there is to it. You can put breakpoints in the above example to figure out which properties you have available and add new ones by enriching your log events if needed. As always please leave a comment down below if this helped you! I will be doing a series on Serilog.