logback 之 创建 RollingFileAppender
最近有需求要将context信息写入文件,以备后续数据分析。本想直接同步写入文件了事,但是logback针对日志的输出性能尤佳,且为异步写入。既然logback封装如此完美,何不直接使用?
?
动态创建Logger及其appender。代码如下:
?
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import ch.qos.logback.classic.Level;import ch.qos.logback.classic.LoggerContext;import ch.qos.logback.classic.encoder.PatternLayoutEncoder;import ch.qos.logback.classic.spi.ILoggingEvent;import ch.qos.logback.core.rolling.RollingFileAppender;import ch.qos.logback.core.rolling.TimeBasedRollingPolicy; Logger logger = LoggerFactory.getLogger(loggerName); LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger newLogger = (ch.qos.logback.classic.Logger)logger; //Remove all previously added appenders from this logger instance. newLogger.detachAndStopAllAppenders(); //define appender RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<ILoggingEvent>(); //policy TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>(); policy.setContext(loggerContext); policy.setMaxHistory(5); policy.setFileNamePattern("/home/lionbule/%d{yyyy-MM-dd}.log"); policy.setParent(appender); policy.start(); //encoder PatternLayoutEncoder encoder = new PatternLayoutEncoder(); encoder.setContext(loggerContext); encoder.setPattern("%message%n"); encoder.start(); //start appender appender.setRollingPolicy(policy); appender.setContext(loggerContext); appender.setEncoder(encoder); appender.setPrudent(true); //support that multiple JVMs can safely write to the same file. appender.start(); newLogger.addAppender(appender); //setup level newLogger.setLevel(Level.WARN); //remove the appenders that inherited 'ROOT'. newLogger.setAdditive(false);
上述代码为草稿,具体使用细节,则根据自己的需求调整。?
?
要点总结:
1. 成功创建appender的关键在于,要实例化一个appender,然后set policy/encoder/&others...
? ? 最后再start appender。
? ? 并且在创建policy时,一定要记住set当前实例化的appender。
? ? 具体步骤看上述demo。
?
?
?