如何为JUnit测试设置Loglevel
我在我的课程中使用java日志。
例:
public class MyClass { private static Logger logger = Logger.getLogger(MyClass.class.getName()); .... }
当我为该课程编写JUnit测试时,我想将Loglevel设置为’FINE’。 我试过了:
@Before public void setup() throws PluginException { Logger.getGlobal().setLevel(Level.FINE); .... }
但这没有效果。 使用Java Logging时,如何在JUnit Test中控制loglevel? 我正在使用Maven运行我的测试。
这是我发现为JUnit测试设置java.util.logging
级别的最简单,最通用的方法。
import java.util.logging.Level; import java.util.logging.Logger; import org.junit.BeforeClass; import org.junit.Test; public class MyTest { @BeforeClass public static void beforeClass() { System.setProperty("java.util.logging.config.file", ClassLoader.getSystemResource("logging.properties").getPath()); } @Test public void test00a() { Logger.getLogger(MyTest.class.getName()).log(Level.FINE, "JUL test"); } }
在src/test/resources
创建logging.properties
( .level
必须是第一行 ):
.level=FINEST handlers=java.util.logging.ConsoleHandler java.util.logging.ConsoleHandler.level=FINEST
当您在此课程中运行unit testing时,您应该看到:
2017年5月1日下午12:17:12 MyTest test00a
精细:JUL测试
Logger.getLogger()文档:
查找或创建指定子系统的记录器。 如果已使用给定名称创建了记录器,则返回该记录器。 否则,将创建一个新的记录器。
在您的情况下,具有相同名称的Logger.getLogger()为您提供相同的logger-instance。 因此,您可以获取记录器并设置其级别
@Before public void setup() throws PluginException { Logger.getLogger(MyClass.class.getName()).setLevel(Level.FINE); ... }
只需确保稍后在@ After-method中将其设置回来。