如何手动创建SiftingAppender

时间:2013-02-13 15:56:33

标签: java logback

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

我尝试创建所有对象,以便复制我之前使用过的相同XML配置。不幸的是,我不明白如何将文件缓冲器附加到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);

1 个答案:

答案 0 :(得分:2)

您必须创建一个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);