From 7925439270473ca759bf64cf4972e8e16e0f25e8 Mon Sep 17 00:00:00 2001 From: maguodong Date: Sat, 28 Mar 2026 09:25:35 +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=E6=8C=89=E5=A4=A9=E8=BD=AE=E8=BD=AC?= =?UTF-8?q?=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 添加 currentDate 和 fileLogger 全局变量用于管理日志文件状态 - 实现 checkAndRotateLogFile 函数检查并切换跨天日志文件 - 集成 lumberjack 日志库支持文件大小和备份管理 - 重构 Init 函数添加日志文件轮转检查逻辑 - 更新日志配置参数为单个文件最大 2MB 最多保留 5 个备份 30 天 --- log/log.go | 41 ++++++++++++++++++++++++++++++++++------- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/log/log.go b/log/log.go index f81da3b..b2ef276 100644 --- a/log/log.go +++ b/log/log.go @@ -16,9 +16,11 @@ import ( ) var ( - logPath string - sysLog *log.Logger - filePath string + logPath string + sysLog *log.Logger + filePath string + currentDate string // 当前日志文件对应的日期 + fileLogger *lumberjack.Logger ) const ( @@ -60,13 +62,38 @@ func (w *logWriter) Write(p []byte) (n int, err error) { return len(p), nil } +// checkAndRotateLogFile 检查是否需要切换日志文件(跨天时) +func checkAndRotateLogFile() { + date := gtime.Date() + if currentDate != date { + // 日期变化,需要重新初始化 + currentDate = date + filePath = gfile.Join(logPath, fmt.Sprintf("log-%s.log", currentDate)) + fileLogger = &lumberjack.Logger{ + Filename: filePath, + MaxSize: 2, // 单个文件最大 10MB + MaxBackups: 5, // 最多保留 5 个备份 + MaxAge: 30, // 保留 30 天 + Compress: false, // 启用压缩 + } + // 创建新的 writer + multiWriter := &logWriter{ + console: os.Stdout, + file: fileLogger, + } + sysLog = log.New(multiWriter, "", 0) + } +} + func Init() { - logPath = gfile.Join(gfile.Pwd(), "logs") - filePath = gfile.Join(logPath, fmt.Sprintf("log-%s.log", gtime.Date())) - if gfile.Exists(filePath) { + if sysLog != nil { + checkAndRotateLogFile() // 检查是否需要切换文件 return } - fileLogger := &lumberjack.Logger{ + logPath = gfile.Join(gfile.Pwd(), "logs") + currentDate = gtime.Date() + filePath = gfile.Join(logPath, fmt.Sprintf("log-%s.log", currentDate)) + fileLogger = &lumberjack.Logger{ Filename: filePath, MaxSize: 2, // 单个文件最大 10MB MaxBackups: 5, // 最多保留 5 个备份