如何在不重新启动应用程序的情况下重新配置Serilog?

Rob*_*aap 8 logging serilog

在长时间运行的进程(例如Windows服务或ASP.NET应用程序)中,有时需要暂时提高日志级别而不停止应用程序.NLog可以监视日志记录配置文件,并在每次修改时重新读取它们.

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

Serilog也可以吗?

Nic*_*rdt 12

使用LoggingLevelSwitch此:

// 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");
Run Code Online (Sandbox Code Playgroud)

更改`levelSwitch.MinimumLevel时,记录器将获取新的最低级别设置.

对于Serilog 1.4.10及更早版本

Serilog并没有将其作为一流的概念加入.

这可以使用过滤器进行模拟:

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

Log.Logger = new LoggerConfiguration()
    .Filter.ByExcluding(evt => (int)evt.Level < (int)minLevel)
    .CreateLogger();
Run Code Online (Sandbox Code Playgroud)

由您决定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; }
}
Run Code Online (Sandbox Code Playgroud)

第二种方法更可取,但如果两台记录器需要共享同一个日志文件,则表现不佳.如果您需要在两种情况下都写入文件,请将较高级别的记录器链接到较低级别的记录器,例如:

var minWarningLogger = new LoggerConfiguration()
    .MinimumLevel.Warning()
    .WriteTo.Sink((ILogEventSink)minVerboseLogger)
    .CreateLogger();
Run Code Online (Sandbox Code Playgroud)

不可否认,这比你联系的NLog方法更复杂; 我会考虑一下如何让它更顺畅.