Search code examples
asp.net-coreserilog

Is there an option in Serilog to change log file parameters in runtime, the same way LogLevel can be changed?


With Serilog in asp.net core you can change the log level in runtine by using

MinimumLevel.ControlledBy(SeriLogLevelSwitch).

Is there a similar way to do this with LoggerConfiguration().WriteTo.File(...)

For instance i need to change the configuration for log fileSizeLimitBytes, or rollingInterval withour restaring the service. Can this be achieved with Serilog?


Solution

  • By pulling in the latest Serilog.AspNetCore you'll find a class called ReloadableLogger, constructed through the CreateBootstrapLogger() extension method:

    // using Serilog;
    var logger = new LoggerConfiguration()
      .WriteTo.File(...)
      .CreateBootstrapLogger();
    
    // Optional but suggested:
    Log.Logger = logger;
    
    // Use the logger...
    
    // Change parameters later on:
    logger.Reload(lc => lc
      .WriteTo.File(...));
    

    You might find that some interactions between CreateBootstrapLogger() and UseSerilog(callback) in ASP.NET Core trip things up a bit; if you use this technique, try the parameterless version of UseSerilog().

    ReloadableLogger has only just appeared and is focusing on a slightly different scenario, so you may still need to work through some awkwardness setting this up - YMMV.