JUnit的Log4j2配置

原文

给JUnit测试提供不同Log4j2配置是很普遍的需求,通常有以下两种做法:

测试目录下放置log4j2-test.xml

Log4j2-Config-for-JUnit

放置log4j2-test.xml文件到src/test/resources目录下,这样可以替换log4j2.xml配置

设置log4j.configurationFile配置

@BeforeClass中配置log4j.configurationFile可以指定加载的log4j配置。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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"));
}
}