功能特性
- 目錄結構:
logs/YYYYMM/DD.log
- 每條記錄帶時間戳:
#HH:mm:ss# [message]
- 自動刪除兩個月前的整月目錄
- 線程安全(
synchronized 鎖檔案寫入)
核心實作
public class WriteLogUtil {
private static final String ROOT = "D:/logs/";
private static final Object LOCK = new Object();
public static void write(String msg) {
synchronized (LOCK) {
deleteOldMonth();
File logFile = getTodayLogFile();
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 File getTodayLogFile() {
LocalDate now = LocalDate.now();
String dir = ROOT + now.format(DateTimeFormatter.ofPattern("yyyyMM"));
String file = dir + "/" + now.format(DateTimeFormatter.ofPattern("dd")) + ".log";
File d = new File(dir);
if (!d.exists()) d.mkdirs();
File f = new File(file);
if (!f.exists()) try { f.createNewFile(); } catch (IOException ignored) {}
return f;
}
private static void deleteOldMonth() {
LocalDate twoMonthsAgo = LocalDate.now().minusMonths(2);
String dir = ROOT + twoMonthsAgo.format(DateTimeFormatter.ofPattern("yyyyMM"));
File d = new File(dir);
if (d.exists()) {
for (File f : d.listFiles()) f.delete();
d.delete(); // 刪除空目錄
}
}
}
改進建議(生產級)
| 問題 | 建議 |
| 同步鎖性能 | 改用 Logback/Log4j2 異步 Appender |
| 日期格式硬編碼 | 使用 DateTimeFormatter 靜態常量 |
| 硬編碼路徑 | 配置檔/環境變數 LOG_ROOT |
| 無日誌級別 | 擴展 write(level, msg),支援 DEBUG/INFO/WARN/ERROR |
| 無滾動策略 | 引入 RollingFileAppender(按大小/時間/壓縮) |
遷移到 SLF4J + Logback(三行配置)
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.11</version>
</dependency>
logs/app.log
logs/%d{yyyyMM}/%d{dd}.log.gz
60
%d{HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
// 代碼中
private static final Logger log = LoggerFactory.getLogger(MyClass.class);
log.info("業務日誌: {}", msg);
何時用手寫工具類
- 極簡專案、無依賴限制、嵌入式環境
- 教學理解日誌原理
- 特殊格式需求(如上傳至專有收集系統)
其他情況強烈建議使用成熟日誌框架。
- 上一篇文章: JPanel 設置背景圖片兩種方案:繼承重寫 paintComponent 與平鋪繪製
- 下一篇文章: Java ArrayList 排序完整指南:Comparator 多條件、Lambda 鏈式與基本類型優化
Copyright ©
程式碼之家 All Rights Reserved