在Logback中将Appender分组?

时间:2013-06-14 15:33:39

标签: java logging slf4j logback appender

我有两个appender。其中一个是DB appender,另一个是SMTPAppender。当我使用特殊标记记录字符串时,我想使用我的自定义db appender和SMTPAppender。但是我不希望每隔两天定义两个appender:

<logger name="com.MyClass" level="DEBUG" additivity="false">
    <appender-ref ref="CUSTOM_DB"/>
    <appender-ref ref="CUSTOM_EMAIL"/>
</logger>

我想要一个特殊的参考,就像那样:

<appender-group ref="CUSTOM_COMBO">
    <appender-ref ref="CUSTOM_DB"/>
    <appender-ref ref="CUSTOM_EMAIL"/>
</appender-group>

<logger name="com.MyClass" level="DEBUG" additivity="false">
    <appender-ref ref="CUSTOM_COMBO"/>
</logger>

它应该调用CUSTOM_DB和CUSTOM_EMAIL。我怎样才能在Logback with slf4j上做到这一点?

2 个答案:

答案 0 :(得分:0)

看起来您需要编写自己的CompoundAppender,有关如何编写自定义appender的详细信息位于http://logback.qos.ch/manual/appenders.html

答案 1 :(得分:0)

所以来自https://tersesystems.com/blog/2019/05/27/application-logging-in-java-part-5/

public class CompositeAppender<E> extends UnsynchronizedAppenderBase<E> implements AppenderAttachable<E> {

    protected AppenderAttachableImpl<E> aai = new AppenderAttachableImpl<E>();

    @Override
    protected void append(E eventObject) {
        aai.appendLoopOnAppenders(eventObject);
    }

    // AppenderAttachable API delegates to aai in all cases
}

<configuration>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>[%-5level] %logger{15} -  message%n%xException{10}</pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>file.log</file>
        <encoder>
            <pattern>%date - %message</pattern>
        </encoder>
    </appender>

    <appender name="CONSOLE_AND_FILE" class="com.tersesystems.logback.CompositeAppender">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="FILE"/>
    </appender>

    <root level="TRACE">
        <appender-ref ref="CONSOLE_AND_FILE"/>
    </root>
</configuration>