1. 简介
在Logback中,推荐使用配置文件(如logback.xml或logback-spring.xml)来设置日志记录的行为。但在实际应用中,会有动态配置logback的需求。此时可通过编程的方式直接操作LoggerContext以及相关的Logger、Appender、Encoder等组件来实现。
2. 代码示例
// step1: 获取LoggerContext的实例,要求其具体实现为logback(通过SPI指定)
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
// step2: 进行设置
try {
// step2.1: 创建RollingFileAppender并进行配置
RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>();
fileAppender.setContext(context);
fileAppender.setFile("/logs/service.log");
// step2.2: 创建滚动策略
TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<>();
rollingPolicy.setContext(context);
rollingPolicy.setFileNamePattern("/logs/service.%d{yyyy-MM-dd}.log");
rollingPolicy.setMaxHistory(30);
fileAppender.setRollingPolicy(rollingPolicy);
rollingPolicy.setParent(fileAppender); // 该条语句非常关键
rollingPolicy.start();
// step2.3: 创建Encoder
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(context);
encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n");
encoder.start();
fileAppender.setEncoder(encoder);
// step2.4: 创建Filter,设定只输出INFO和ERROR级别
LevelFilter infoFilter = new LevelFilter();
infoFilter.setContext(context);
infoFilter.setLevel(Level.INFO);
infoFilter.setOnMatch(FilterReply.ACCEPT);
infoFilter.setOnMismatch(FilterReply.NEUTRAL);
infoFilter.start();
LevelFilter errorFilter = new LevelFilter();
errorFilter.setContext(context);
errorFilter.setLevel(Level.ERROR);
errorFilter.setOnMatch(FilterReply.ACCEPT);
errorFilter.setOnMismatch(FilterReply.DENY);
errorFilter.start();
fileAppender.addFilter(infoFilter);
fileAppender.addFilter(errorFilter);
// step2.5: 启动FileAppender
fileAppender.start();
// step2.6: 配置ROOT的日志级别以及Appender
context.getLogger(Logger.ROOT_LOGGER_NAME).addAppender(fileAppender);
context.getLogger(Logger.ROOT_LOGGER_NAME).setLevel(Level.INFO);
} catch (Exception e) {
throw new RuntimeException(e);
}