由于log4j僅在appender是RollingFileAppender時maxBackupIndex才有效窄瘟;所以本文根據(jù)自己的需要具垫, 擴展log4j自帶的DailyRollingFileAppender,增加對maxBackupIndex參數(shù)的支持帝洪。
注意:需要重寫DailyRollingFileAppender的rollOver方法似舵,但是此方法是default的,所以需要建一個同名包才能繼承重寫這個方法葱峡,即項目結(jié)構(gòu)應(yīng)該如下圖砚哗,使用與DailyRollingFileAppender完全相同:
項目結(jié)構(gòu)
使用
完整代碼如下:
/**
* @Description: 擴展DailyRollingFileAppender,增加對 maxBackupIndex參數(shù)的支持
* @Author: Li - Robin
* @Date: 2021/2/19 14:52
*/
public class DailyRollingFileAppender2 extends DailyRollingFileAppender {
/**
* 保留的備份文件個數(shù)(最近幾個)
*/
protected int maxBackupIndex;
public void setMaxBackupIndex(int maxBackupIndex) {
this.maxBackupIndex = maxBackupIndex;
}
public int getMaxBackupIndex() {
return maxBackupIndex;
}
@Override
public void activateOptions() {
super.activateOptions();
//無特殊處理砰奕,僅僅打印下maxBackupIndex
if (this.maxBackupIndex != 0) {
LogLog.debug("Appender maxBackupIndex=" + maxBackupIndex);
}
}
/**
* 在原來的滾動生成規(guī)則上增加文件個數(shù)判斷蛛芥,刪除多余的文件
*
* @throws IOException
*/
@Override
void rollOver() throws IOException {
super.rollOver();
if (this.maxBackupIndex <= 0) {
return;
}
File file = new File(this.fileName);
String simpleFileName = file.getName();
File parentPath = new File(file.getParent());
// check path
if (!parentPath.exists()) {
LogLog.error("Appender file: " + fileName + " don't exist");
return;
}
AtomicInteger fileCount = new AtomicInteger(this.maxBackupIndex);
try (Stream<File> files = Stream.of(parentPath.listFiles())) {
//過濾出以simpleFileName 開頭的文件,且不包含simpleFileName 本身
files.filter(logFile -> !logFile.getName().equals(simpleFileName) && logFile.getName().startsWith(simpleFileName))
//按照修改時間倒敘
.sorted((l1, l2) -> Long.valueOf(l2.lastModified()).compareTo(l1.lastModified()))
//保留前 maxBackupIndex 個文件
.forEach(logFile -> {
if (fileCount.getAndDecrement() > 0) {
//保留最近的文件
return;
}
try {
//刪除多余的文件
logFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}