【发布时间】:2022-01-09 04:37:49
【问题描述】:
这里是 SSCCE 添加 SLF4J LOGGER 消息并抛出空指针异常。它使用列表附加器来检查日志:
package my.tester;
import org.junit.jupiter.api.Assertions;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
public class TestException {
public static void main(String[] args) {
final Logger LOGGER = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("TestException");
final ListAppender<ILoggingEvent> listAppender = new ListAppender<>();
listAppender.start();
LOGGER.addAppender(listAppender);
NullPointerException testException = new NullPointerException("Oops!");
LOGGER.info("doing stuff");
LOGGER.error("problem here", testException);
Assertions.assertTrue(listAppender.list.get(1).getFormattedMessage().contains("Oops"));
}
}
日志追加器中只有两行:
doing stuff
problem here
因此,检查异常的测试自然会失败,输出如下:
16:45:15.577 [main] INFO TestException - doing stuff
16:45:15.591 [main] ERROR TestException - problem here
java.lang.NullPointerException: Oops!
at my.texter.TestException.main(TestException.java:34)
Exception in thread "main" org.opentest4j.AssertionFailedError: expected: <true> but was: <false>
at org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:40)
at org.junit.jupiter.api.AssertTrue.assertTrue(AssertTrue.java:35)
at org.junit.jupiter.api.Assertions.assertTrue(Assertions.java:162)
at my.texter.TestException.main(TestException.java:39)
如何将来自 null 异常的堆栈跟踪添加到日志中?
【问题讨论】:
-
LOGGER.error("这里有问题", testException);这将从异常中打印堆栈跟踪,因为您的类只有 1 个调用,所以您在堆栈跟踪中只看到一行。
-
谢谢,但与我的问题无关
标签: java logging slf4j stack-trace