Serilog, Change the loglevel at runtime for a specific namespace (> MinimumLevel)

Each of your MinimumLevel.Override can have its own LoggingLevelSwitch, which allows you to control the log level for each particular override at run-time.

Create individual LoggingLevelSwitch for each override that you intend to modify whilst the app is running, and store these instances in a place that you can access from other parts of your application, which will allow you to change the MinimumLevel of these LoggingLevelSwitch(es).

e.g.

public class LoggingLevelSwitches
{
    // Logging level switch that will be used for the "Microsoft" namespace
    public static readonly LoggingLevelSwitch MicrosoftLevelSwitch
        = new LoggingLevelSwitch(LogEventLevel.Warning);

    // Logging level switch that will be used for the "Microsoft.Hosting.Lifetime" namespace
    public static readonly LoggingLevelSwitch MicrosoftHostingLifetimeLevelSwitch
        = new LoggingLevelSwitch(LogEventLevel.Information);
}

Configure your Serilog logging pipeline to use these LoggingLevelSwitch instances:

static void Main(string[] args)
{
    Log.Logger = new LoggerConfiguration()
        .MinimumLevel.Override("Microsoft", LoggingLevelSwitches.MicrosoftLevelSwitch)
        .MinimumLevel.Override("Microsoft.Hosting.Lifetime",
            LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch)
        .Enrich.FromLogContext()
        .CreateLogger();

    // ...
}

Then somewhere in your application, for example, in the code that handles your application configuration that can be changed at run-time, update the LoggingLevelSwitch instance(s) to the new LogEventLevel that you want:

public class AppSettings
{
    void ChangeLoggingEventLevel()
    {
        LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
            .MinimumLevel = LogEventLevel.Error;

        LoggingLevelSwitches.MicrosoftHostingLifetimeLevelSwitch
            .MinimumLevel = LogEventLevel.Warning;

        // ...
    }
}

As you can see, the LogEventLevel is controlled by the LoggingLevelSwitch instances, so it's up to you to decide where in your application (and how) these instances will be modified, to affect the logging pipeline.

The example above I'm assuming you have a screen (or API) in your application that a user would be able to configure the logging levels.

If you don't have that, then another approach is to have a background thread that periodically checks a configuration file, an environment variable, or query a database, etc. to determine what these logging levels should be.

If you're using a .NET Core Host, you can use the Options pattern which can handle the refresh of the configuration for you, and allow you to execute code when the configuration changes (where you'd change the MinimumLevel of your LoggingLevelSwitch(es) you have.

Tags:

Serilog