How can I reconfigure Serilog without restarting the application?

In a lengthy process (such as a Windows service or ASP.NET application), it is sometimes desirable to temporarily increase the level log without stopping the application. NLog can monitor the logging of configuration files and reread them every time they are changed.

https://github.com/nlog/NLog/wiki/Configuration-file#automatic-reconfiguration

Is this also possible with Serilog ?

+4
source share
1 answer

Use LoggingLevelSwitchfor this:

// Set initial level
var levelSwitch = new LoggingLevelSwitch(LogEventLevel.Warning);

Log.Logger = new LoggerConfiguration()
  .MinimumLevel.ControlledBy(levelSwitch)
  .WriteTo.Console()
  .CreateLogger();

Log.Debug("This is not shown");

levelSwitch.MinimumLevel = LogEventLevel.Debug;

Log.Debug("This will now be shown, since the level has changed");

When the `levelSwitch.MinimumLevel parameter is changed, the log records a new minimum level.

For Serilog 1.4.10 and earlier

Serilog .

:

// Stored e.g. in a static field
volatile LogEventLevel minLevel;

Log.Logger = new LoggerConfiguration()
    .Filter.ByExcluding(evt => (int)evt.Level < (int)minLevel)
    .CreateLogger();

, , minLevel .

, , , .

, , :

var minVerboseLogger = new LoggerConfiguration()
    .MinimumLevel.Verbose()
    .CreateLogger();

var minWarningLogger = new LoggerConfiguration()
    .MinimumLevel.Warning()
    .CreateLogger();

// Somewhere else:
public ILogger Log
{
    get { return isVerbose ? minVerboseLogger : minWarningLogger; }
}

, , . , , :

var minWarningLogger = new LoggerConfiguration()
    .MinimumLevel.Warning()
    .WriteTo.Sink((ILogEventSink)minVerboseLogger)
    .CreateLogger();

, , NLog; - , .

+5

All Articles