Excluding logs from Serilog

Serilog is great! Sending the logs to Seq so you can analyze them easily and create cool dashboards is great! Using Azure Monitor to test the availability of your website (or API in my case) is great!

But spamming your logs with the call to the health endpoint every five minutes is quite useless. Luckily, there’s an easy fix.

The Serilog setup in the host builder should be something as follows:

hostBuilder.UseSerilog((webHostBuilderContext, loggerConfiguration) =>
{
  loggerConfiguration = loggerConfiguration
    .ReadFrom.Configuration(webHostBuilderContext.Configuration);
}

First, by installing the Serilog.Filters.Expressions NuGet package we can add expression filters to include or, in our case, exclude certain items from our logs.

After that’s done it’s as easy as adding a single exclusion line to our Serilog configuration builder. Since we’re already using the Serilog.AspNetCore NuGet package to enhance our Serilog events with ASP.NET Core related data, we know that it adds additional properties to each log event during our entire request pipeline. Conveniently, one of them is the RequestPath. So all we need to do is add an exclusion rule checking the request path.

So we extend our configuration as follows:

hostBuilder.UseSerilog((webHostBuilderContext, loggerConfiguration) =>
{
  loggerConfiguration = loggerConfiguration
    .ReadFrom.Configuration(webHostBuilderContext.Configuration)
    .Filter.ByExcluding(
      x => x.Properties.Any(
        y => y.Key == "RequestPath"
        && y.Value.ToString().Contains("/health")));
}
comments powered by Disqus