我有一个测试,我想记录一些测试信息。我设法使用基本的 Java 记录器做到了这一点,但我做错了什么。每个后续条目日志消息都会成倍增加,即。第一条消息被记录一次,第二条被记录两次,第三条被记录三次,等等,我不确定我做错了什么。消息也被推送到控制台,但只有一次。
public class MyExampleTest {
private FileHandler fh = null;
private static final Logger logger = Logger.getLogger(MyExampleTest.class.getName());
SimpleFormatter formatter = new SimpleFormatter();
@Test
public void infoPackage() throws Exception {
fh = new FileHandler("test.log", true);
// do some test stuff
writeEntryToLogFile("entry one");
// do some more test stuff
writeEntryToLogFile("entry two");
// do even more test stuff
writeEntryToLogFile("entry three");
}
private void writeEntryToLogFile(String message) throws Exception {
fh.setFormatter(formatter);
logger.addHandler(fh);
logger.info(message);
}
}
我的日志文件最终是这样的:
entry one
entry two
entry two
entry three
entry three
entry three
我想我把文件处理程序弄乱了,但我不知道是什么。
最佳答案
每次调用 writeEntryToLogFile()
时都会添加一个处理程序。
所以每次调用都会有一个额外的重复输出。
您应该添加一个设置方法,您可以在其中为每个执行的测试设置上下文。
您使用的 JUnit 允许使用 @Before
注释:
@Before
public void setup() {
fh = new FileHandler("test.log", true);
formatter = new SimpleFormatter();
fh.setFormatter(formatter);
logger.addHandler(fh);
}
附带说明一下,不断言任何内容的测试方法没有任何意义。
关于java - 为什么每个后续日志条目都会重复(使用 java.util.logging)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44503257/