專案常需將日誌寫入檔案,並按日期分目錄儲存、定期清理舊檔。本文提供一個 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+)更安全。