在Junit测试期间如何将日志级别设置为DEBUG? [英] How to set the log level to DEBUG during Junit tests?
问题描述
我正在使用SLF4J和LOG4J,配置通常在 log4j.properties
中,它将日志级别设置为INFO。
I am using SLF4J with LOG4J, and the configurations are usually in the log4j.properties
, and it sets the log level to INFO.
但是在测试期间我想将日志设置为DEBUG。
However during the tests I would like to set the logs to DEBUG.
我看不到自动化这种方法的方法,也没有有类似 log4j.tests.properties
的东西,只会在测试期间加载。
I can't see a way to automate this, neither to have something like log4j.tests.properties
that would be loaded only during tests.
所以我试过做这在编程设置中(@BeforeClass):
So I've tried doing this programmatically in the test setup (the @BeforeClass):
LogManager.getRootLogger().setLevel(Level.ALL);
没有成功......
With no success...
我使用的是这些版本:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
如何实现这一结果?
编辑:我认为我不够清楚。这个问题不是关于设置正确的日志级别...它是关于在运行Junit测试时设置DEBUG日志级别,以及在任何其他情况下设置INFO日志级别。我想自动执行此操作。
I think I wasn't clear enough. This question is not about setting the correct log level... It is about setting the DEBUG log level when running Junit tests, and setting INFO log level in any other situation. I want to automate this.
推荐答案
您无需为JVM提供不同的日志实现。
You do not need to give the JVM a different log implementation.
日志记录代码使用类路径搜索 log4j.properties
文件。因此,您需要做的就是确保您的测试 log4j.properties
文件位于发布文件之前的位置。
The logging code searches for the log4j.properties
file using the classpath. So all you need to do is ensure that your test log4j.properties
file is in a location that it will find before the release file.
我使用Maven,它在目录中放置文件以使其变得容易。我的发布 log4j.properties
进入目录 src / main / resources
。我的测试版本在 src / test / resources
中。 Eclipse构建路径(类路径)设置为在 src / main / resources
之前搜索 src / test / resources
,所以你的单元测试使用测试文件。 JAR(或WAR)构建指令使用 src / main / resources
中的文件。
I use Maven, which lays out files in directories to make that easy. My release log4j.properties
goes in the directory src/main/resources
. My test version goes in src/test/resources
. The Eclipse build path (classpath) is set up to search src/test/resources
before src/main/resources
, so your unit tests use the test file. The JAR (or WAR) build instructions use the files from src/main/resources
.
这篇关于在Junit测试期间如何将日志级别设置为DEBUG?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!