How to dynamically change log level in SLF4j Log4J with Standalone Java Class

LogLevel change based on the log level choosen

Posted by Prateep Gedupudi on December 12, 2015

Many of us already know this, but logging is just a way of monitoring our application, and when used right this can provide you with information of what is happening during application’s runtime process.

We can log errors and actions applications encounter, which is pretty critical. Logging other things can be very informative e.g. the start and end of a batch process, amount of processed files, duration within a certain method call and so on.

We want the right kinds of information available to us, but don’t want to store tons of old logs that don’t mean anything to us a year later. We want to try to write concise informative messages that are self-explanatory and able to be dumped soon after, as needed.

Here are some of logging levels

  • ERROR label for actual errors
  • WARN for potential issues that can interfere with correct workings of the application but will not crash it.
  • INFO for messages announcing the start of your batch process
  • DEBUG and TRACE for all other things we don’t want to read in the future or only when really needed, like the type of implementations of certain interfaces loaded on startup. I believe if we are using the DEBUG or TRACE level to actually debug our application, we probably should have written a unit test that verifies that part of code we wrote full with debug statements

Facade vs. Implementation

JUL, Log4j 1.2, Log4j 2 and Logback are full-blown logging implementations. We can just use these directly. Apache Commons Logging and SLF4J are facades over actual logging implementations. Each of them does include an internal, simplistic logging implementation (“SimpleLog” for Commons Logging, “Simple” for SLF4J) but we are meant to use a real implementation in production

Slf4j and Log4j Binding

Changing LogLevel Dynamically

We do not have a way to change log level from slf4j api and we need to rely on implementation, in our case log4j api. First get rootLogger with log4j then set the level on it. Here is an example code for the same


		logger.info("Sample Info");
		logger.debug("Sample Debug");
		logger.error("Sample Error");
		logger.trace("Sample Trace");
		logger.warn("Sample Warn");
		
		org.apache.log4j.Logger logger4j = org.apache.log4j.Logger.getRootLogger();
		logger4j.setLevel(org.apache.log4j.Level.toLevel("ERROR"));
				
		logger.info("Sample Info After setLevel");
		logger.debug("Sample Debug After setLevel");
		logger.error("Sample Error After setLevel");
		logger.trace("Sample Trace After setLevel");
		logger.warn("Sample Warn After setLevel");
Code Download