【问题标题】:Can a stack trace exception be added to SLF4J LOGGER?可以将堆栈跟踪异常添加到 SLF4J LOGGER 吗?
【发布时间】: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


【解决方案1】:

尝试改变

LOGGER.error("这里有问题", testException);

LOGGER.error("这里有问题", testException,testException);

【讨论】:

  • 添加 testException 一次或多次添加,在检查 appender 时不会添加任何额外内容。以上是SSCCE,因此任何有兴趣的人都可以轻松测试。
  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
猜你喜欢
  • 1970-01-01
  • 2011-01-05
  • 2017-08-06
  • 2010-09-13
  • 2019-11-05
  • 1970-01-01
  • 2010-09-18
  • 2010-09-17
相关资源
最近更新 更多