正在静默忽略java Logback内部异常
我在学习JAVA,今天我在玩Logback。作为一个练习,我编写了一个定制的“appender”,将日志(用于Spring)写入MongoDB集合。在跟踪一个bug之后,我发现如果我的appender抛出一个异常,那么这个异常就会被默默地忽略,应用程序会继续运行,但相关的记录器现在已经死亡
引发异常的位置:
public class MongoDBAppender extends AppenderBase<ILoggingEvent> {
...
protected void append(ILoggingEvent event) {
...
throw new RuntimeException("My example exception!");
由于我想在一开始就打开一个MongoDB会话,然后开始日志记录,然后启动Spring,所以我以编程方式设置了这个appender:
MongoClient mongoClient = new MongoClient("localhost:27017");
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
PatternLayoutEncoder ple = new PatternLayoutEncoder();
ple.setContext(lc);
ple.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger - %msg%n");
ple.start();
MongoDBAppender mongoDBAppender = new MongoDBAppender();
mongoDBAppender.setContext(lc);
mongoDBAppender.setEncoder(ple);
mongoDBAppender.setmongoDBName("test");
mongoDBAppender.setmongoDBCollectionName("my_log");
mongoDBAppender.start();
Logger logger = (Logger) LoggerFactory.getLogger("org.springframework");
logger.addAppender(mongoDBAppender);
logger.setLevel(Level.INFO);
logger.setAdditive(false);
其他记录器在^{
因此,这个应用程序可以正常运行,但没有为org.springframework
记录任何内容。如果我将logback.xml
文件的开头更改为:
<configuration debug="true">
然后,我从Logback本身获得一个完整的调试输出,然后我确实看到我的异常被抛出
Is there any way to get this sort of output if and only if there is an error?
# 1 楼答案
经过一些挖掘,似乎
AppenderBase
中的doAppend
方法捕获异常并将其记录到内部回写日志中:只有在使用<configuration debug="true">
选项时才会显示。doAppend
方法实际上是调用我的自定义append
的方法我的解决方法是:自己在
append
中捕获所有异常,然后将它们记录到我自己的记录器(用于MongoDBAppender)。然后我们可以决定如何(或是否)显示这些消息