Dynamic Log Level per Context

730 views
Skip to first unread message

Michael Peter

unread,
Feb 5, 2016, 10:26:03 AM2/5/16
to Serilog
Hi 

I am looking into Serilog to replace our current logging in our webshop application. However there seems no way to enable dynamic log levels on a per context basis. Am I missing something here?`

Right now we are using log4net and we use the static log-per-type approach which servers us well. At the moment we have a couple hundred log instances. On our productions servers the default log level is warn and if we need to, we can dynamically change the log level in order to gather the information we need. It does not happen very often, but once in a while we need to change log levels to debug for certain logs and let it run a couple of days to catch esoteric bugs, often related to 3rd party systems. 

Changing the log level to debug for the whole application is prohibitively expensive for us in terms of space (can reach megabytes per second) and performance (as additional backend and database calls are made to gather information). 

As far as I can see Serilog does not have the ability to control the log level in per Context manner. Is there a way around this and if not is this going to change in future releases? 

Best regards,
Michael

Ian Yates

unread,
Feb 6, 2016, 6:01:50 AM2/6/16
to Serilog
You can achieve this by chaining loggers.

Have a global singleton logger which is set to verbose level.

Then in each of your classes you effectively do

LoggingLevelSwitch logLevel = new LoggingLevelSwitch();

ILogger byTypeLogger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(logLevel)
.WriteTo.Logger(theGlobalVerboseLogger)





Some IoC wiring can make this quite elegant :)  However the key concept is to have some logger that knows to write to files, Seq, etc and it has a minimum level of verbose.  Then you have your other loggers write to this "accepts anything" logger.  It's those other loggers where you can set up default enrich properties and use the LoggingLevelSwitch to govern what events actually get through these secondary loggers.  Note that the LoggingLevelSwitch defaults to "Information" level.

Hope that helps!

nblum...@nblumhardt.com

unread,
Feb 7, 2016, 6:11:32 PM2/7/16
to Serilog
+1 to Ian's solution. So long as you don't write directly to the "global, verbose" logger, this approach should have negligible perf impact (events will only be generated when the context-specific loggers are "on", etc.)

It'd be nice to wrap this up in some kind of logger factory code for your scenario, of course :-)

Let us know if you need any more info!

Michael Peter

unread,
Feb 8, 2016, 5:03:06 AM2/8/16
to Serilog
Thanks for your replies!

It's all clear to me now!

Reply all
Reply to author
Forward
0 new messages