问题
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.
回答1:
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 test log4j.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 directory src/main/resources. My test version goes in src/test/resources. The Eclipse build path (classpath) is set up to search src/test/resources before src/main/resources, so your unit tests use the test file. The JAR (or WAR) build instructions use the files from src/main/resources.
回答2:
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.
回答3:
You can use the org.apache.logging.log4j.core.config.Configurator which has a setAllLevels method.
In your test you can use it in a @Before method:
@Before
public void changeLogLevel() {
Configurator.setAllLevels("", Level.ALL);
}
NOTE: tested with binding org.slf4j:slf4j-log4j12:1.7.26
回答4:
Below ROOT log level change will work for junit to set logging to desired level.
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
@Before
public void setUp() {
final Logger logger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
logger.setLevel(Level.ALL);
}
来源:https://stackoverflow.com/questions/38778026/how-to-set-the-log-level-to-debug-during-junit-tests