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.
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.
To change log levels as a root user, perform the following: To enable debug logging, run the following command: /subsystem=logging/root-logger=ROOT:change-root-log-level(level=DEBUG) To disable debug logging, run the following command: /subsystem=logging/root-logger=ROOT:change-root-log-level(level=INFO)
Launch Event Viewer. Select View\Show Analytic and Debug Logs. Navigate to Event Viewer (Local)\Applications and Service Logs\Microsoft\User Experience Virtualization\App Agent. Right-click on Debug under App Agent and select Enable Log.
In Settings -> Config Vars set logging. level.com. yourpackage to the desired level (INFO, ERROR, DEBUG).
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
.
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With