In the Serilog project we’re frequently asked how to adjust the logging level at runtime, and until recently we haven’t had a great answer.
Many larger/distributed apps need to run at a fairly restricted level of logging, say,
Information (my preference) or
Warning, and only turn up the instrumentation to
Verbose when a problem has been detected and the overhead of collecting a bit more data is justified.
Setting the level to its minimum (
Verbose) and dynamically filtering events has been our suggestion so far, and it does save on network or disk I/O bandwidth, but the overhead of generating the events in the first place is still a significant consideration.
In Serilog 1.4.11, there’s a new type,
LoggingLevelSwitch that provides this feature with very minimal performance overhead.
If an app needs dynamic level switching, the first thing to create is an instance of this type:
var levelSwitch = new LoggingLevelSwitch();
You need to keep the switch around in an accessible place.
This object defaults the current minimum level to
Information, so if you want to be more restricted, set its minimum level up-front:
levelSwitch.MinimumLevel = LogEventLevel.Warning;
Now, when configuring the logger, provide the switch using
var log = new LoggerConfiguration() .MinimumLevel.ControlledBy(levelSwitch) .WriteTo.ColoredConsole() .CreateLogger();
Now, events written to the logger will be filtered according to the switch’s
If you need to turn the level up or down at runtime, perhaps in response to a command sent over the network, it’s as easy as:
levelSwitch.MinimumLevel = LogEventLevel.Verbose; log.Verbose("This will now be logged");