package utils import ( "fmt" "io" "os" "path/filepath" "time" "github.com/sirupsen/logrus" ) var ( Logger = logrus.New() currentLogFile *os.File currentLogDay string ) func InitLogger() { if err := os.MkdirAll("log", 0755); err != nil { panic(fmt.Sprintf("创建日志目录失败: %v", err)) } // 初始化日志文件 rotateLog() } // 添加新的rotateLog函数用于日志文件轮转 func rotateLog() { today := time.Now().Format("2006-01-02") // 如果是同一天的日志文件,直接返回 if today == currentLogDay && currentLogFile != nil { return } // 关闭之前的日志文件 if currentLogFile != nil { currentLogFile.Close() } // 创建新的日志文件 logFileName := filepath.Join("log", today+".log") logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644) if err != nil { panic(fmt.Sprintf("打开日志文件失败: %v", err)) } // 更新当前日志文件和日期 currentLogFile = logFile currentLogDay = today Logger.SetFormatter(&logrus.JSONFormatter{}) Logger.SetOutput(io.MultiWriter(os.Stdout, logFile)) } func LogAccess(ip, path, method string, userInfo map[string]interface{}) { // 检查是否需要轮转日志文件 rotateLog() // 设置东八区时区 loc, err := time.LoadLocation("Asia/Shanghai") if err != nil { Logger.WithError(err).Error("Failed to load timezone") return } // 获取当前时间并格式化为东八区时间,使用中国人的习惯格式 now := time.Now().In(loc) timestamp := now.Format("2006-01-02 15:04:05") // 构建日志字段 fields := logrus.Fields{ "ip": ip, "path": path, "method": method, "timestamp": timestamp, } // 合并用户信息到日志字段中 if userInfo != nil { for k, v := range userInfo { fields[k] = v } } // 记录日志 Logger.WithFields(fields).Info("Page accessed") }