A Serilog sink that exposes a simple interface to retrieve and change LoggingLevelSwitches at runtime.
To get started install the Serilog.Sinks.DynamicSwitch package:
PM> Install-Package Serilog.Sinks.DynamicSwitch
or
dotnet add package Serilog.Sinks.DynamicSwitch
A DynamicSwitch sink can be set up in the standard way while constructing a LoggerConfiguration
. A specific DynamicSwitchCollection
object can be passed to the configuration; if one is not specified, a static global collection is used that be referenced using DynamicSwitchCollection.Current
. Each DynamicSwitch must be uniquely named. The following is a simple example:
var logLevel = new LoggingLevelSwitch(LogEventLevel.Warning);
var log = new LoggerConfiguration()
.WriteTo.Console(levelSwitch: logLevel)
.WriteTo.DynamicSwitch("Test", logLevel)
.CreateLogger();
If using appsettings.json
for configuration, the following example shows how to configure DynamicSwitch sinks along with attached level switches:
{
"Serilog": {
"Using": ["Serilog.Sinks.DynamicSwitch"],
"LevelSwitches": {
"$appLogLevel": "Debug",
"$netLogLevel": "Information",
"$sysLogLevel": "Error"
},
"MinimumLevel": {
"ControlledBy": "$appLogLevel",
"Override": {
"Microsoft": "$netLogLevel",
"System": "$sysLogLevel"
}
}
"WriteTo": [{
"Name": "Console"
},
{
"Name": "DynamicSwitch",
"Args": {
"switchName": "Application",
"levelSwitch": "$appLogLevel"
}
},
{
"Name": "DynamicSwitch",
"Args": {
"switchName": "Microsoft",
"levelSwitch": "$netLogLevel"
}
},
{
"Name": "DynamicSwitch",
"Args": {
"switchName": "System",
"levelSwitch": "$sysLogLevel"
}
}
],
"Properties": {
"Application": "Serilog DynamicSwitch Console Sample"
}
}
}
To support the retrieval of switches through dependency injection, there is a simple extention method to add the collection to the services container. If a collection is not passed, the global DynamicSwitchCollection.Current
will be added to the container:
.ConfigureServices((hostContext, services) =>
{
//...
services.AddDynamicSwitches();
});
MIT