在logback.xml中设置SiftingAppender时如何使用记录器

时间:2019-07-15 12:40:43

标签: java logback

我有此登录配置:

<appender name="SIFT" class="ch.qos.logback.classic.sift.SiftingAppender">
    <discriminator class="com.blackHole.programmingTrading.config.ThreadNameBasedDiscriminator"/>
    <sift>
        <appender name="FILE-${threadName}" class="ch.qos.logback.core.FileAppender">
            <file>${LOG_HOME}/app-${threadName}.log</file>
            <layout class="ch.qos.logback.classic.PatternLayout">
                <pattern>${UNION_LOG_PATTERN}</pattern>
            </layout>
        </appender>
    </sift>
</appender>

,并具有以下配置类:

public class ThreadNameBasedDiscriminator implements Discriminator<ILoggingEvent> {
    private static final String KEY = "threadName";
    private boolean started;

    @Override
    public String getDiscriminatingValue(ILoggingEvent iLoggingEvent) {
        return iLoggingEvent.getThreadName();
    }

    @Override
    public String getKey() {
        return KEY;
    }

    public void start() {
        started = true;
    }

    public void stop() {
        started = false;
    }

    public boolean isStarted() {
        return started;
    }
}

但是当我得到这样的记录器时:

LoggerFactory.getLogger(Logger.class)

或者这个:

LoggerFactory.getLogger("SIFT")

siftAppender不起作用,我还有其他的附加程序一起工作,那么如何处理呢?

1 个答案:

答案 0 :(得分:1)

使用相同的设置,仅使用如下所示的记录器即可完美工作;

@Component
public class SomeService {

    public void test() {
        Logger logger = LoggerFactory.getLogger(SomeService.class);
        logger.error("hey");
    }
}

然后我可以在本地的app-myThread.log中看到日志;

14:43:01.808 [myThread]   ERROR com.example.demo.SomeService - hey

如果您想获得一个特定名称的记录器,则需要在logback.xml中添加以下内容;

<logger name="mylogger" level="error">
    <appender-ref ref="SIFT"/>
</logger>

由于appender != logger,您可以为此添加自己的配置...

那你就可以做

LoggerFactory.getLogger("mylogger");

将导致日志有所不同;

14:53:23.447 [myThread]   ERROR mylogger - hey