Using different log4j2 configuration file for junit testing is desired by most of the developers. Let’s learn some recommended ways to configure Log4j2 – specific to junit testcases and different from used in production.
Table of Contents Place log4j2-test.xml in test folder Use log4j.configurationFile property in @BeforeClass
Place log4j2-test.xml in test folder
Place the log4j2-test.xml
file in src/test/resources
folder. By placing a log4j2-test.xml
into this directory will cause it to be used instead of a log4j2.xml
or log4j2.json
that might be present.

Use log4j.configurationFile property in @BeforeClass
Another way to introduce different log file for junit tests is – to set log4j.configurationFile
property in @BeforeClass
annotation in any test class.
E.g. Create test specific logging configuration file log4j2-testConfig.xml
and place it in resources
folder. Now let use this file in JUnit tests.
import java.net.MalformedURLException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; public class HelloWorldTest { private static Logger LOGGER = null; @BeforeClass public static void setLogger() throws MalformedURLException { System.setProperty("log4j.configurationFile","log4j2-testConfig.xml"); LOGGER = LogManager.getLogger(); } @Test public void testOne() { LOGGER.debug("Debug Message Logged !!!"); LOGGER.info("Info Message Logged !!!"); LOGGER.error("Error Message Logged !!!", new NullPointerException("NullError")); } }
Drop me your questions related to log4j2 configuration for junit tests in comments section.
Happy Learning !!
Niranjan
thanks this works.
I had missed setting System.setProperty(“log4j.configurationFile”,”log4j2-testConfig.xml”);
Deepak Khobragade
Hi Lokesh,
My log4j2 configuration is set up in such a way that it creates log files dynamically in tomcat/logs folder (using Routing Appenders). I have written a unit test and have a separate Log4j2 config file for that, but when I run the Junit test, the log4j2 does not creates any file in the tomcat/logs folder. Can you please help with creating the logs from the junit tests?
Thank You!
Deepak
Lokesh Gupta
What is current configuration?