LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
SiftingAppender siftingAppender = new SiftingAppender();
siftingAppender.setContext(loggerContext);
siftingAppender.setName("SIFTING_APPENDER");
MDCBasedDiscriminator discriminator = new MDCBasedDiscriminator();
discriminator.setKey("SIFT_KEY");
discriminator.setDefaultValue("SIFT_KEY_DEF");
discriminator.start();
siftingAppender.setDiscriminator(discriminator);
siftingAppender.setAppenderFactory(new AppenderFactory<ILoggingEvent>() {
@Override
public Appender<ILoggingEvent> buildAppender(Context context, String discriminatingValue) throws JoranException {
RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
appender.setName("ROLLING_APPENDER_"+discriminatingValue);
appender.setContext(context);
appender.setFile("/var/log/activeLog_"+discriminatingValue+".log");
TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>();
policy.setContext(context);
policy.setMaxHistory(2);
policy.setFileNamePattern("/var/log/archivedLog_"+discriminatingValue+"_%d{yyyy_MM_dd_HH_mm}_%i.log");
policy.setParent(appender);
policy.setCleanHistoryOnStart(true);
SizeAndTimeBasedFNATP<ILoggingEvent> innerpolicy = new SizeAndTimeBasedFNATP<>();
innerpolicy.setContext(context);
innerpolicy.setMaxFileSize("5KB");
innerpolicy.setTimeBasedRollingPolicy(policy);
policy.setTimeBasedFileNamingAndTriggeringPolicy(innerpolicy);
policy.start();
appender.setRollingPolicy(policy);
PatternLayoutEncoder pattern = new PatternLayoutEncoder();
pattern.setContext(context);
pattern.setPattern("%d{yyyy/MM/dd'T'HH:mm:ss} %-5level - %msg\n");
pattern.start();
appender.setEncoder(pattern);
appender.start();
return appender;
}
});
siftingAppender.start();
ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger("org.test");
logger.addAppender(siftingAppender);
logger.setLevel(Level.DEBUG);
logger.setAdditive(false); /* set to true if root should log too */
MDC.put("SIFT_KEY", "SIFTED1");
logger.info("bla11.........................");
logger.info("bla12.........................");
logger.info("bla13.........................");
MDC.clear();
MDC.put("SIFT_KEY", "SIFTED2");
logger.info("bla21.........................");
logger.info("bla22.........................");
logger.info("bla23.........................");
MDC.clear();