Recently I encountered a situtation where Application Loglevel changes dynamically. Application Admin can set it to INFO/DEBUG/ WARN from front end. Based on the log level choosen be him application logging must be changed.
I am sure loggers support this scenario, but not sure how can I achive this. If any of you have idea/thoughts on this please let me know.
Thanks in advance for your help.
-Narendra
Consider Logback http://logback.qos.ch/ - "a successor to the popular log4j project, picking up where log4j leaves off". If instructed to do so, logback-classic will scan for changes in its configuration file and automatically reconfigure itself when the configuration file changes. Besides, you can control Logback's logging levels with JMX.
It is not possible to change the log level dynamically in slf4j, but some backends for slf4j support it, including log4j.
This solution worked for me:
org.apache.log4j.Logger logger4j = org.apache.log4j.Logger.getRootLogger();
logger4j.setLevel(org.apache.log4j.Level.toLevel("ERROR"));
(Source: http://prateep.info/2015/12/12/Dynamically-change-log-level-in-SLF4j-Log4J-with-Standalone-Java-Class/)
The disadvantage of this solution is that it uses the backend directly, which you're not supposed to do when using slf4j because the point of slf4j is to provide an abstraction away from the specific backend you're using.
I had to do this once with log4j. The only way I could figure out how to do it was to call getAllAppenders on the Logger object. Then, loop through the appenders. If they extend the AppenderSkeleton class (they should), they will have the setThreshold method. Call this method with your new Level as the parameter. Subsequent calls to the logger should use the new level. This will set the level in memory, but not in your log4j configuration file. You may want to do this, too, unless it gets changed automatically when the admin changes the level via the front end. If it's an option, you may want to consider following Evgeniy Dorofeev's advice and use logback. It sounds like it would be easier.