2

I'm migrating a legacy app to use logback, in the process I'm trying to keep all of the old functionality working in the same way. One thing the legacy app did was log to the console if the log file could not be written (due to lack of space, bad permissions, etc)

With logback it seems a StatusListener should handle this, I can use getOrigin to get the sifted appender, but I can't figure out how to get the logger associated with the origin appender. Is it possible?

logback.xml:

<statusListener class="com.example.LogStatusListener"/>

<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  <encoder>
    <pattern>WARNING: %logger is only being logged to CONSOLE!%n%msg%n</pattern>
  </encoder>
</appender>

<appender name="FILE-SIMPLE" class="ch.qos.logback.classic.sift.SiftingAppender">
  <discriminator class="com.example.CustomDiscriminator"/>
  <sift>
    <appender name="FILE-${logfile}" class="ch.qos.logback.core.rolling.FileAppender">
      <file>${logfile}.log</file>
      <encoder>
        <pattern>%msg%n</pattern>
      </encoder>
    </appender>
  </sift>
</appender>

<logger name="debug">
  <appender-ref ref="FILE-SIMPLE" />
</logger>

Listener:

public class LogStatusListener implements StatusListener {
    @Override
    public void addStatusEvent(Status status) {
        if (status instanceof ErrorStatus) {
            System.err.println(status);
            if (status.getOrigin() instanceof Appender) {
                Appender origin = (Appender) status.getOrigin();
                if (!origin.isStarted()) {
                    // find the logger associated with origin, and add ConsoleAppender
                }
            }
        }
    }
}
4

1 回答 1

2

组件都可以生成状态消息,而不仅仅是 appender。状态消息没有与之关联的记录器,因此您无法获取状态消息的记录器。顺便说一下,logback 实现了从 I/O 错误中优雅的恢复。例如,如果磁盘已满,logback 将停止记录,并在磁盘上有可用空间时自动重新开始记录。请注意,在此期间发生的日志记录事件会丢失。

于 2012-05-29T14:00:57.360 回答