Configure Log4j2 for JUnit Tests

Learn to use a different Log4j2 configuration file for JUnit tests is a recommended approach. We can apply two ways to configure Log4j2 specific to tests and that is different from the production logging config file.

1. Place log4j2-test.xml in test/resources 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 in ‘src/main/resources‘ folder.

Log4j2 Config for JUnit
Log4j2 Config for JUnit

2. Load from external locations with ‘log4j.configurationFile‘ Property

Another way to introduce a different log configuration file is – to set log4j.configurationFile property in @BeforeAll annotation in any test class.

For example, we can create test specific logging configuration file log4j2-testConfig.xml and place it in some external folder. Now let use this file in JUnit tests.


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;

	public static void setLogger() throws MalformedURLException
		LOGGER = LogManager.getLogger();

	public void testOne()
		//test code

Drop me your questions related to log4j2 configuration for junit tests in the comments section.

Happy Learning !!

Leave a Reply

Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial