Spring Boot入门:【Spring Boot+LogBack】高效记录日志,实现日志文件本地化保存!
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;
public class LogConfig {
public static void configLog() {
// 获取日志上下文
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
// 创建一个滚动文件appender
RollingFileAppender rollingFileAppender = new RollingFileAppender<>();
rollingFileAppender.setContext(loggerContext);
rollingFileAppender.setName("memberAppender");
// 设置滚动策略
TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy<>();
rollingPolicy.setContext(loggerContext);
rollingPolicy.setParent(rollingFileAppender);
rollingPolicy.setFileNamePattern("logs/member.log.%d{yyyy-MM-dd}.%i");
rollingPolicy.setMaxHistory(10);
rollingPolicy.setTotalSizeCap(10 * 1024 * 1024); // 10 MB
rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(
TimeBasedRollingPolicy.DAILY);
// 设置布局编码器
PatternLayoutEncoder encoder = new PatternLayoutEncoder();
encoder.setContext(loggerContext);
encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss} %-5level %logger{36} - %msg%n");
encoder.start();
// 关联滚动策略和编码器
rollingFileAppender.setRollingPolicy(rollingPolicy);
rollingFileAppender.setEncoder(encoder);
// 设置日志级别
rollingFileAppender.setAppend(true);
rollingFileAppender.setTriggeringPolicy(rollingPolicy);
rollingFileAppender.setContext(loggerContext);
rollingFileAppender.start();
// 设置日志级别
ch.qos.logback.classic.Logger logger =
loggerContext.getLogger("com.myapp.member");
logger.addAppender(rollingFileAppender);
logger.setLevel(Level.INFO);
// 刷新日志配置
loggerContext.reset();
}
}
这段代码展示了如何使用LogBack来配置一个会每天滚动并且最多保留10天日志的Appender。同时,它设置了日志的格式和级别,并且通过LoggerContext
来刷新日志配置。这是一个简化版本的日志配置,适合入门学习和实际生产环境的基本需求。
评论已关闭