logback的日志输出配置如下
<!-- 日志文件输出 -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${log.base}/${log.moduleName}.log
</File><!-- 设置日志不超过${log.max.size}时的保存路径,注意如果 是web项目会保存到Tomcat的bin目录 下 -->
<!-- 滚动记录文件,先将日志记录到指定文件,当符合某个条件时,将日志记录到其他文件。-->
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<FileNamePattern>${log.base}/archive/${log.moduleName}_all_%d{yyyy-MM-dd}.%i.log.zip
</FileNamePattern>
<!-- 当天的日志大小 超过${log.max.size}时,压缩日志并保存 -->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${log.max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>${log.max.history}</maxHistory>
</rollingPolicy>
<!-- 日志输出的文件的格式 -->
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>%date{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread]%logger{56}.%method\(\):%L -%msg%n</pattern>
</layout>
</appender>
其中如下定义了压缩和历史日志的保存策略,有两个比较重要的参数:maxFileSize,maxHistory
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>${log.max.size}</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
<maxHistory>${log.max.history}</maxHistory>
先看一下继承关系图
maxHistory默认为0,由源码可以看出(TimeBasedRollingPolicy-start()),只有不为0并且清理任务开启标志位true时会触发清理操作
if (maxHistory != INFINITE_HISTORY) {
archiveRemover = timeBasedFileNamingAndTriggeringPolicy.getArchiveRemover();
archiveRemover.setMaxHistory(maxHistory);
if(cleanHistoryOnStart) {
addInfo("Cleaning on start up");
archiveRemover.clean(new Date(timeBasedFileNamingAndTriggeringPolicy.getCurrentTime()));
}
}
清理过程会先计算需要清理的时间范围
int computeElapsedPeriodsSinceLastClean(long nowInMillis) {
long periodsElapsed = 0;
//如果尚未执行过清理操作,则默认清理除保留天数外64天以内的日志(由INACTIVITY_TOLERANCE_IN_MILLIS决定)
if (lastHeartBeat == UNINITIALIZED) {
addInfo("first clean up after appender initialization");
periodsElapsed = rc.periodsElapsed(nowInMillis, nowInMillis + INACTIVITY_TOLERANCE_IN_MILLIS);
if (periodsElapsed > MAX_VALUE_FOR_INACTIVITY_PERIODS)
periodsElapsed = MAX_VALUE_FOR_INACTIVITY_PERIODS;
} else {
//如果已经执行过清理操作,则清理从上次到当前时间的需要清理的时间周期。
periodsElapsed = rc.periodsElapsed(lastHeartBeat, nowInMillis);
if (periodsElapsed < 1) {
addWarn("Unexpected periodsElapsed value " + periodsElapsed);
periodsElapsed = 1;
}
}
return (int) periodsElapsed;
}
接着就会按天来清理
public void clean(Date now) {
long nowInMillis = now.getTime();
int periodsElapsed = computeElapsedPeriodsSinceLastClean(nowInMillis);
lastHeartBeat = nowInMillis;
if (periodsElapsed > 1) {
addInfo("periodsElapsed = " + periodsElapsed);
}
//按天清理
for (int i = 0; i < periodsElapsed; i++) {
//periodOffsetForDeletionTarget=-maxHistory-1,如maxHistory为2,则该值为-3
cleanByPeriodOffset(now, periodOffsetForDeletionTarget - i);
}
}
删除时会根据当天时间,生成一个正则表达式:/*****/rsms_all_2018-04-09.(\d{1,3}).log.zip,满足条件的文件就会被清理掉。
由以上可以得出两个结论
- 如果首次项目启动时,超出maxHistory定义的时间的64天之前的日志是不会被清理的
-
如果当天日志的编号超出3位数后缀,也将不会被清理