log4j按日期生成文件+控制文件個(gè)數(shù) maxBackupIndex

由于log4j僅在appender是RollingFileAppender時(shí)maxBackupIndex才有效;所以本文根據(jù)自己的需要, 擴(kuò)展log4j自帶的DailyRollingFileAppender,增加對(duì)maxBackupIndex參數(shù)的支持。

注意:需要重寫(xiě)DailyRollingFileAppender的rollOver方法,但是此方法是default的,所以需要建一個(gè)同名包才能繼承重寫(xiě)這個(gè)方法,即項(xiàng)目結(jié)構(gòu)應(yīng)該如下圖,使用與DailyRollingFileAppender完全相同:

項(xiàng)目結(jié)構(gòu)

使用

完整代碼如下:

/**
 * @Description: 擴(kuò)展DailyRollingFileAppender,增加對(duì) maxBackupIndex參數(shù)的支持
 * @Author: Li - Robin
 * @Date: 2021/2/19 14:52
 */
public class DailyRollingFileAppender2 extends DailyRollingFileAppender {

    /**
     * 保留的備份文件個(gè)數(shù)(最近幾個(gè))
     */
    protected int maxBackupIndex;

    public void setMaxBackupIndex(int maxBackupIndex) {
        this.maxBackupIndex = maxBackupIndex;
    }

    public int getMaxBackupIndex() {
        return maxBackupIndex;
    }

    @Override
    public void activateOptions() {
        super.activateOptions();
        //無(wú)特殊處理,僅僅打印下maxBackupIndex
        if (this.maxBackupIndex != 0) {
            LogLog.debug("Appender maxBackupIndex=" + maxBackupIndex);
        }
    }

    /**
     * 在原來(lái)的滾動(dòng)生成規(guī)則上增加文件個(gè)數(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())) {
            //過(guò)濾出以simpleFileName 開(kāi)頭的文件,且不包含simpleFileName 本身
            files.filter(logFile -> !logFile.getName().equals(simpleFileName) && logFile.getName().startsWith(simpleFileName))
                    //按照修改時(shí)間倒敘
                    .sorted((l1, l2) -> Long.valueOf(l2.lastModified()).compareTo(l1.lastModified()))
                    //保留前 maxBackupIndex 個(gè)文件
                    .forEach(logFile -> {
                        if (fileCount.getAndDecrement() > 0) {
                            //保留最近的文件
                            return;
                        }
                        try {
                            //刪除多余的文件
                            logFile.delete();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容