Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set log4j log level

I'm currently working on a project that uses log4j. I'm running a testcase (junit) and would like to set the log level to trace so that I can see if all the values are correct. Classes that use logging in the project contain a line like the following:

private static final Log LOG = LogFactory.getLog(MatchTaskTest.class); 

and use a like like this to do the actual debugging

LOG.trace("value"); 

I have never used log4j before, does anybody know how I can change the log level just for the testcase, preferably simply by defining a parameter in eclipse's run configuration dialog.

like image 612
Konstantin Weitz Avatar asked May 17 '12 23:05

Konstantin Weitz


People also ask

How do I change log level in log4j?

Setting Levels using Configuration File log4j provides you configuration file based level setting which sets you free from changing the source code when you want to change the debugging level. Following is an example configuration file which would perform the same task as we did using the log. setLevel(Level.

What is the default log level in log4j?

Note that by default Log4j assigns the root logger to Level. ERROR.

How do you change the log level in log4j2 at runtime?

You can set a logger's level with the class Configurator from Log4j Core. BUT be aware that the Configurator class is not part of the public API. If you wish to change the root logger level, do something like this : LoggerContext ctx = (LoggerContext) LogManager.


1 Answers

Using another configuration file

Perhaps you could point to another configuration file.

java -Dlog4j.configuration=config file yourApp 

Where:

  • config, you file of configuration, e.g. log4j.properties or log4j.xml.
  • file, the log file, e.g. myApp.log
  • yourApp, you app, e.g. MyAppGUI

Or you can use a class

java -Dlog4j.configurationClass=config class yourApp 

Where:

  • config, you file of configuration, e.g. log4j.properties or log4j.xml.
  • class, any customized initialization class, like LogManager, should implement the org.apache.log4j.spi.Configurator
  • yourApp, you app, e.g. MyAppGUI

You can see more in Apache log4j 1.2 - Short introduction to log4j on Default Initialization Procedure section.

Modifying the level programmatically

Moreover, you can also use the methods that offers the Logger class, like public void setLevel(Level level), e.g.:

Logger.getRootLogger().setLevel(Level.TRACE); 

Since you want only for testing purposes, you could use them. But it is recommended not to use in client code because they overwrite the default configuration parameters in hard coded. The best way is to use an external configuration file.

like image 50
Paul Vargas Avatar answered Oct 16 '22 16:10

Paul Vargas