gpt4 book ai didi

java - 如何手动创建 SiftingAppender

转载 作者:行者123 更新时间:2023-11-30 09:26:45 32 4
gpt4 key购买 nike

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

我尝试创建所有对象以复制我之前使用过的相同 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);

最佳答案

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

关于java - 如何手动创建 SiftingAppender,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14857558/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com