I am using SLF4J with LOG4J, and the configurations are usually in the log4j.properties
, and it sets the log level to INFO.
However during the tests I would like to set the logs to DEBUG.
I can't see a way to automate this, neither to have something like log4j.tests.properties
that would be loaded only during tests.
So I've tried doing this programmatically in the test setup (the @BeforeClass):
LogManager.getRootLogger().setLevel(Level.ALL);
With no success...
I am using these versions:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
How can I achieve this result?
EDIT: I think I wasn't clear enough. This question is not about setting the correct log level... It is about setting the DEBUG log level when running Junit tests, and setting INFO log level in any other situation. I want to automate this.
Usually LEVEL.FINEST should do it... but take a look to http://saltnlight5.blogspot.mx/2013/08/how-to-configure-slf4j-with-different.html to see logging frameworks implementations considereation.
You can use the
org.apache.logging.log4j.core.config.Configurator
which has asetAllLevels
method.In your test you can use it in a
@Before
method:NOTE: tested with binding org.slf4j:slf4j-log4j12:1.7.26
You do not need to give the JVM a different log implementation.
The logging code searches for the
log4j.properties
file using the classpath. So all you need to do is ensure that your testlog4j.properties
file is in a location that it will find before the release file.I use Maven, which lays out files in directories to make that easy. My release
log4j.properties
goes in the directorysrc/main/resources
. My test version goes insrc/test/resources
. The Eclipse build path (classpath) is set up to searchsrc/test/resources
beforesrc/main/resources
, so your unit tests use the test file. The JAR (or WAR) build instructions use the files fromsrc/main/resources
.Below ROOT log level change will work for junit to set logging to desired level.
maybe not entirely related to the question in the first place, however a google query will lead most developers to this topic when they search for a way on
how to change the log level for certain junit test methods.
The way to go is to use a custom junit MethodRule that accesses the loggers and re-configures the log level per package.
With below classes, you can achieve this. It sets the log level for packages and classes as defines in the annotation of a test method and when the test has finished, sets the loggers back to their initial state. We assume the default log level is set to INFO currently.
To achieve this, you need so specify the test rule in your test class:
Classes needed found below: