Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change log4net logging level programmatically

This is similar to 650694 but no answer was accepted there, I can't get any of those suggestions to work at all, and I suspect I may be in a slightly different situation.

I'm calling log4net.Config.XmlConfigurator.Configure(). But after that point in the program, I want to change the logging threshold to a value only known at runtime.

From the other question, I tried:

((log4net.Repository.Hierarchy.Logger)mylogger.Logger).Level = log4net.Core.Level.Error;

and:

var appender = new log4net.Appender.ColoredConsoleAppender();
appender.Layout = new log4net.Layout.PatternLayout(@"%date %-5level %message%newline");
appender.Threshold = log4net.Core.Level.Error;
appender.ActivateOptions();
log4net.Config.BasicConfigurator.Configure(appender);

but neither one seems to have any effect: I'm still seeing DEBUG and INFO logging statements on the console.

My hunch is that I'm adding a new appender, which has no effect on the appender declared in the XML config (which tells it to print DEBUG level messages), but I don't have any evidence for this yet.

I've been digging through the log4net API for a while now, and I'm just not seeing it. Is there something simple I'm missing?

like image 364
Ken Avatar asked Apr 03 '09 22:04

Ken


3 Answers

None of these solutions present here worked for me. It wasn't changing at runtime

Here is what worked for me:

((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).Root.Level = Level.Debug;
((log4net.Repository.Hierarchy.Hierarchy)LogManager.GetRepository()).RaiseConfigurationChanged(EventArgs.Empty);

You have to call RaiseConfigurationChanged after making changes to its config.

like image 115
JeanT Avatar answered Sep 25 '22 00:09

JeanT


Finally found a working solution, here.

The big pieces were:

  • need to set the threshold on all loggers, including the "cannot be retrieved by name" root logger
  • need to get the Level from the Hierarchy's LevelMap

Big thanks to Eddie for asking good pointed questions, which led me to google the right words. I never would have figured this out alone.

(Aside: Repository, Hierarchy, Logger, RootLogger, LevelMap -- I had no idea it was even possible to make a logging library this complex. It's got about 20 layers of indirection, which I'm sure makes it flexible enough for anything, but makes it nearly impossible to do simple things like "don't log any messages above threshold X". Gah!)

like image 21
Ken Avatar answered Sep 23 '22 00:09

Ken


There's a simple way to do it:

LogManager.GetRepository().Threshold = Level.Info;

More information can be found here.

like image 26
Alex Avatar answered Sep 27 '22 00:09

Alex