Issue
I have some unit test written in my project I wanted to change the logging behaviour for unit test so I created a log4j2-test.xml in src/test/resources but I am not able to see any change in my logging behaviour. I wanted to check that whether my test file is recognising this configuration or not. Is there any way to do that?
Here is the code snippet.
This is the code for log4j2-test.xml file
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %c:%L - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error" >
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
This is the sample test code
@Slf4j
@Test
public void sampleTest()
{
log.info("Hello World");
log.error("Bye World")
assertEquals(1*5,5);
}
The ideal behaviour should be that "Bye world" log should be printed but not the "Hello World" log but I always see both the log. Is there any way I can check in my test that whether that configuration is picked or not?
Solution
To check which configuration is picked there are two ways:
- In your log4j2-test.xml file you can just set the status of Configuration tag to TRACE and it will print internal Log4j2 logging to the console including internal logging that took place before the configuration file was found.
- You can alternatively run your application through IntelliJ by setting the VM arguments as
-Dlog4j2.debug=true
According to log4j2 official documentation
The level of internal Log4j events that should be logged to the console. Valid values for this attribute are "off", "trace", "debug", "info", "warn", "error", "fatal", and "all". Log4j will log details about initialisation, rollover and other internal actions to the status logger. Setting status="trace" is one of the first tools available to you if you need to troubleshoot log4j.
Alternatively, setting system property log4j2.debug will also print internal Log4j2 logging to the console, including internal logging that took place before the configuration file was found.
Answered By - codersaty
Answer Checked By - Cary Denson (JavaFixing Admin)