From abf552901914993f43a942390748bd3fcb7097c3 Mon Sep 17 00:00:00 2001 From: maguodong Date: Sat, 28 Mar 2026 09:44:58 +0800 Subject: [PATCH] =?UTF-8?q?feat(log):=20=E6=B7=BB=E5=8A=A0=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E6=96=87=E4=BB=B6=E8=87=AA=E5=8A=A8=E6=B8=85=E7=90=86?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现 cleanOldLogs 函数用于删除指定天数之前的日志文件 - 添加日志文件名格式匹配逻辑,只处理 log-YYYY-MM-DD.log 格式的文件 - 在日志文件切换时自动清理 30 天前的过期日志文件 - 在系统启动时执行一次日志清理操作 - 添加日志输出显示已删除的过期日志文件信息 --- log/log.go | 30 +++++++++++++++++++++++++----- 1 file changed, 25 insertions(+), 5 deletions(-) diff --git a/log/log.go b/log/log.go index f3539df..31e1104 100644 --- a/log/log.go +++ b/log/log.go @@ -63,7 +63,7 @@ func (w *logWriter) Write(p []byte) (n int, err error) { return len(p), nil } -// cleanOldLogs 删除指定天数之前的日志文件 +// cleanOldLogs 删除指定天数之前的日志文件(包括主文件和备份文件) func cleanOldLogs(days int) { if !gfile.Exists(logPath) { return @@ -81,13 +81,33 @@ func cleanOldLogs(days int) { if gfile.IsDir(path) { continue } - // 匹配日志文件名格式:log-YYYY-MM-DD.log - if !strings.HasPrefix(file, "log-") || !strings.HasSuffix(file, ".log") { + + var dateStr string + var matched bool + + // 匹配主日志文件格式:log-YYYY-MM-DD.log + if strings.HasPrefix(file, "log-") && strings.HasSuffix(file, ".log") { + // 检查是否是主文件(没有备份时间戳) + // 主文件格式:log-2026-04-25.log + // 备份文件格式:log-2026-04-25-2026-04-25T10-30-45.123.log + parts := strings.Split(strings.TrimSuffix(file, ".log"), "-") + if len(parts) == 4 { + // 主文件:log-YYYY-MM-DD + dateStr = parts[1] + "-" + parts[2] + "-" + parts[3] + matched = true + } else if len(parts) > 4 { + // 备份文件:log-YYYY-MM-DD-YYYY-MM-DDTHH-MM-SS.mmm + // 提取主日期部分(第一个日期) + dateStr = parts[1] + "-" + parts[2] + "-" + parts[3] + matched = true + } + } + + if !matched { continue } - // 提取日期部分 - dateStr := strings.TrimSuffix(strings.TrimPrefix(file, "log-"), ".log") + // 解析日期 fileTime, err := time.Parse("2006-01-02", dateStr) if err != nil { continue // 日期格式不正确,跳过