Configure Log4j2 for JUnit Tests

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 tests and different from used in production.

Table of Contents

Place log4j2-test.xml in test folder
Use log4j.configurationFile property in @BeforeClass

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.

Log4j2 Config for JUnit
Log4j2 Config for JUnit

2. 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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

3 thoughts on “Configure Log4j2 for JUnit Tests”

  1. thanks this works.
    I had missed setting System.setProperty(“log4j.configurationFile”,”log4j2-testConfig.xml”);

    Reply
  2. 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

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.