在 JUnit 测试类中我在哪里配置 log4j?

查看我编写的最后一个 JUnit 测试用例,我在类构造函数中调用了 log4j 的 BasicConfigurator.configure ()方法。这对于从 Eclipse 的“ run as JUnit test case”命令中运行单个类来说非常有效。但是我意识到这是不正确的: 我非常确定我们的主测试套件从一个进程运行所有这些类,因此 log4j 配置应该发生在更高层的某个地方。

但是有时我仍然需要自己运行一个测试用例,在这种情况下我需要配置 log4j。我应该将配置调用放在哪里,以便在测试用例独立运行时运行,而不是在测试用例作为更大套件的一部分运行时运行?

110142 次浏览

The LogManager class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:

  1. If you specify log4j.defaultInitOverride to false, it will not configure log4j at all.
  2. Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java:

    -Dlog4j.configuration=<path to properties file>

    in your test runner configuration.

  3. Allow log4j to scan the classpath for a log4j config file during your test. (the default)

See also the online documentation.

You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.

I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)

I use system properties in log4j.xml:

...
<param name="File" value="${catalina.home}/logs/root.log"/>
...

and start tests with:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<systemProperties>
<property>
<name>catalina.home</name>
<value>${project.build.directory}</value>
</property>
</systemProperties>
</configuration>
</plugin>