首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 日誌記錄工具類:依日期分目錄、自動清理舊檔

     編輯:Java 相關知識

前言

專案常需將日誌寫入檔案,並按日期分目錄儲存、定期清理舊檔。本文提供一個 WriteLogUtil 類別,示範單例模式、同步寫入、自動建立目錄、保留最近兩個月日誌。

核心程式碼

public class WriteLogUtil {
    private static final String ROOT = "D:\\logs\\";

    public static synchronized void write(String msg) {
        deleteOldLogs();
        File logFile = getLogFile();
        try (FileWriter fw = new FileWriter(logFile, true)) {
            String time = String.format("%tH:%tM:%tS", new Date(), new Date(), new Date());
            fw.write("#" + time + "# [" + msg + "]\r\n");
        } catch (IOException e) { e.printStackTrace(); }
    }

    private static void deleteOldLogs() {
        int month = (Calendar.getInstance().get(Calendar.MONTH) + 1) - 2;
        if (month <= 0) month += 12;
        File dir = new File(ROOT + month);
        if (dir.exists()) {
            for (File f : dir.listFiles()) f.delete();
        }
    }

    private static File getLogFile() {
        Calendar cal = Calendar.getInstance();
        String dirName = ROOT + (cal.get(Calendar.MONTH) + 1);
        String fileName = String.format("%tY%tm%td.log", cal, cal, cal);
        File dir = new File(dirName);
        if (!dir.exists()) dir.mkdirs();
        File file = new File(dir, fileName);
        if (!file.exists()) try { file.createNewFile(); } catch (IOException ignored) {}
        return file;
    }
}

使用方式

WriteLogUtil.write("使用者登入成功");
WriteLogUtil.write("資料庫連線失敗: " + e.getMessage());

改進建議

  • 使用 log4j2、Logback 等成熟日誌框架,支援滾動策略、非同步寫入、結構化日誌。
  • 若需自行實作,建議採用 BlockingQueue + 背景執行緒批次寫入,降低 I/O 阻塞。
  • 日期格式化改用 DateTimeFormatter(Java 8+)更安全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved