2

我想手动管理 logback 配置——特别是我想在必要时创建一个具有 FileAppender 的新 SiftingAppender。

我尝试创建所有对象以复制我之前使用过的相同 XML 配置。不幸的是,我不明白如何将 fileappender 附加到 siftappender。

这是我正在使用的代码:

LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(loggerContext);
encoder.setPattern("<%d(yyyy-MM-dd HH:mm:ss)> | %.-1level | %msg %n");
encoder.start();

FileAppender<ILoggingEvent> fAppender = new FileAppender<ILoggingEvent>();
fAppender.setContext(loggerContext);
fAppender.setName(application + "_" + user);
fAppender.setFile(logUser);
fAppender.setAppend(true);
fAppender.setEncoder(encoder);
fAppender.start();

MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator();
discriminator.setKey("userid");
discriminator.setDefaultValue("unknown");
discriminator.start();

LevelFilter lFilter = new LevelFilter();
lFilter.setLevel(Level.INFO);
lFilter.start();

// **HOW TO ATTACH fAppender on sAppender ????**
SiftingAppender sAppender = new SiftingAppender();
sAppender.setContext(loggerContext);
sAppender.setName(application + "_" + user + "_SIFTING");
sAppender.addFilter(lFilter);
sAppender.setDiscriminator(discriminator);
sAppender.start();

Logger logger = loggerContext.getLogger("test.mypackage");
logger.setAdditive(false);
logger.setLevel(Level.ALL);
logger.addAppender(sAppender);
4

1 回答 1

3

您必须创建一个 appenderFactory 并将这个工厂添加到 siftingAppender :

    SiftingAppender siftAppender = new SiftingAppender();

    AppenderFactory<ILoggingEvent> appenderFactory = new AppenderFactory<ILoggingEvent>() {

        @Override
        public Appender<ILoggingEvent> buildAppender(Context context, String discriminatingValue) throws JoranException {
            /* Create your file appender here, with what ever options you need */

            PatternLayoutEncoder ple = new PatternLayoutEncoder();
            ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
            ple.setContext(context);
            ple.start();
            FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
            fileAppender.setFile(file);
            fileAppender.setEncoder(ple);
            fileAppender.setContext(context);
            fileAppender.start();

            return fileAppender;
        }
    };

    /* set your factory to the sifting appender */
    siftAppender.setAppenderFactory(appenderFactory );
    siftAppender.setContext(context);
    siftAppender.setName("TMP");
    siftAppender.start();

    logger.addAppender(siftAppender);
    logger.setAdditive(true);
于 2015-11-25T11:02:05.490 回答