C# - Serilog, how to set log level based on a condition

It took me much longer to realize a solution to this problem than I want to admit. I had something like the following in my code and wanted to change the log level depending on the environment to keep info in Dev:

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Information()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
    .WriteTo
    .Console()
    .CreateLogger();

I was certain there was going to be a parameter on .MinimumLevel.Information() and .MinimumLevel.Override() so that we can keep the builder pattern as is. However, I never found a way to do this and ended up in a solution where I split up the configuration like the following:

var isDev = true; //simplified
var loggerConfiguration = new LoggerConfiguration();

if (isDev)
{
    loggerConfiguration
       .MinimumLevel.Information()
       .MinimumLevel.Override("Microsoft", LogEventLevel.Information);
} else
{
    loggerConfiguration
       .MinimumLevel.Warning()
       .MinimumLevel.Override("Microsoft", LogEventLevel.Warning);
}

Log.Logger = loggerConfiguration
    .WriteTo
    .Console()
    .CreateLogger();

The above is quite self explanatory, I have split the builder pattern into different parts, then put an if/else clause to set log levels depending on the environment.

You can also set different types of exclusions based on log event properties if setting a log level is not enough for what you want to do. Sometimes you want to keep some info logs, but not all.

If you want to change the log level dynamically at runtime, check out this post on how to do that.

That is all

That is all, I hope you found this post helpful, please leave a comment down below with your thoughts! Also if you have a better solution please put it down below, this is the best I could come up with.