Change logger/sink configuration at runtime?
See original GitHub issueIs there a straightforward way to change the logger configuration (or sink configuration) at runtime?
I generally set up my main logger with a rolling file sink to print out critical errors (especially at startup) as this works in most scenarios. Independently of what type of application I have (service, website, console), I only need to ensure the file system is write-able and I’m good to go.
// dummy
var logfilepath = GetLogFilePath(Assembly.GetEntryAssembly());
Log.Logger = new LoggerConfiguration()
.WriteTo.RollingFile(logfilepath)
.CreateLogger();
Log.Debug("It works!");
However, I also would like to log into other sources that are more prone to fail at startup (e.g. databases when wrong connection strings are given). So what I would like to achieve is the following:
- Set up a simple, stable logging sink for first startup
- Set up e.g. database, log everything related to it
- If e.g. database is up and running, add database sink to serilog.
The only way I see to accomplish this is:
- Create a logger configuration
- Do stuff
- Create a new logger configuration and overwrite the existing one.
Dummy code:
var logfilepath = GetLogFilePath(Assembly.GetEntryAssembly());
Log.Logger = new LoggerConfiguration()
.WriteTo.RollingFile(logfilepath)
.CreateLogger();
Log.Debug("It works!");
Log.Debug("Setting up database with {ConnectionString}", connectionString);
Log.Logger = new LoggerConfiguration()
.WriteTo.RollingFile(logfilepath)
.WriteTo.SomeDatabaseSink(connectionString)
.CreateLogger();
Is there a cleaner, more straightforward approach to change the logger configuration other than overwriting it completely?
Issue Analytics
- State:
- Created 8 years ago
- Reactions:4
- Comments:8 (7 by maintainers)
Thanks for the weigh-in @damianh. I agree there are some rough edges around this scenario, especially existing contextual loggers, as you point out. I think the way existing loggers continue to point to the sinks they were created with falls out from the immutable/stateless design, which isn’t ideal here but brings a lot of other benefits. Do you think your workaround is something that could be made general? It seems like the best approach available at this point… 😃
I think the new
WriteTo.Logger()
method added in the latest Serilog gets rid of your casting issue:Here’s one option that’s debatably better:
Instead of letting the old logger drop, the new one just redirects to it.
It’s not ideal, but if you set up enrichment etc. on the second (rather than the first) logger it might cut a bit of duplication/noise out. It also has the property of being less likely to cause file locking issues.
👍 or 👎 ?