logback 踩坑

  1. totalSizeCap 配置大于 2GB 时,不生效的问题

logbakc.xml 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<appender name="info_rolling"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<File>${logger.path}/info.log</File>
<encoder charset="${logger.charset}">
<pattern>${logger.pattern}</pattern>
</encoder>
<filter class="ch.qos.logback.classic.filter.LevelFilter">
<level>INFO</level>
<onMatch>ACCEPT</onMatch>
<onMismatch>DENY</onMismatch>
</filter>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>
${logger.path}/info.%d{yy-MM-dd}.%i.log
</fileNamePattern>
<maxHistory>${logger.maxHistory}</maxHistory>
<maxFileSize>512MB</maxFileSize>
<totalSizeCap>5GB</totalSizeCap>
</rollingPolicy>
</appender>

logback-core-1.1.11.jar 及之前版本的 TimeBasedArchiveRemover

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void capTotalSize(Date now) {
int totalSize = 0;
int totalRemoved = 0;
for (int offset = 0; offset < maxHistory; offset++) {
Date date = rc.getEndOfNextNthPeriod(now, -offset);
File[] matchingFileArray = getFilesInPeriod(date);
descendingSortByLastModified(matchingFileArray);
for (File f : matchingFileArray) {
long size = f.length();
if (totalSize + size > totalSizeCap) {
addInfo("Deleting [" + f + "]" + " of size " + new FileSize(size));
totalRemoved += size;
f.delete();
}
totalSize += size;
}
}
addInfo("Removed " + new FileSize(totalRemoved) + " of files");
}

这里的totalSize使用的是int类型,Interger.MAX_VALUE最大只能表示2GB的数据,修改成使用long类型可以解决这个问题。

logback-core 1.2.0 之后的版本已经修复这个问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void capTotalSize(Date now) {
long totalSize = 0;
long totalRemoved = 0;
for (int offset = 0; offset < maxHistory; offset++) {
Date date = rc.getEndOfNextNthPeriod(now, -offset);
File[] matchingFileArray = getFilesInPeriod(date);
descendingSortByLastModified(matchingFileArray);
for (File f : matchingFileArray) {
long size = f.length();
if (totalSize + size > totalSizeCap) {
addInfo("Deleting [" + f + "]" + " of size " + new FileSize(size));
totalRemoved += size;
f.delete();
}
totalSize += size;
}
}
addInfo("Removed " + new FileSize(totalRemoved) + " of files");
}
  • 本文作者: forever杨
  • 本文链接: https://blog.yl-online.top/posts/15985cf3.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。如果文章内容对你有用,请记录到你的笔记中。本博客站点随时会停止服务,请不要收藏、转载!