Logback 内部异常被静默忽略

Logback internal exception being silently ignored

我在学习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 开始,我以编程方式设置此附加程序:

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);

其他记录器在logback.xml中照常定义。

因此,按原样,此应用程序运行正常,但未记录 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?

经过一些挖掘,AppenderBase 中的 doAppend 方法似乎捕获了异常并将它们记录到内部 Logback 日志中:只有在我们使用 <configuration debug="true"> 选项。 doAppend 方法实际上调用了我的自定义 append.

我的解决方法:在 append 中自己捕获所有异常,然后将它们记录到我自己的记录器(对于 MongoDBAppender)。然后我们可以决定如何(或是否)显示此类消息。