package log import ( "context" "fmt" "github.com/gin-gonic/gin" "github.com/spf13/viper" "go.uber.org/zap" "go.uber.org/zap/zapcore" "os" "path/filepath" "strings" "time" ) const ctxLoggerKey = "zapLogger" // ServiceType 服务类型 type ServiceType int const ( API ServiceType = iota // API服务 Task // Task服务 ) type Logger struct { *zap.Logger } // NewLog 创建一个新的日志实例,兼容旧版本配置 func NewLog(conf *viper.Viper) *Logger { return NewServiceLog(conf, API) } // NewServiceLog 创建特定服务类型的日志实例 func NewServiceLog(conf *viper.Viper, serviceType ServiceType) *Logger { var logPath string // 从环境变量检查服务类型 envServiceType := os.Getenv("SERVICE_TYPE") if envServiceType == "api" { serviceType = API } else if envServiceType == "task" { serviceType = Task } // 根据服务类型和日期生成日志文件名 logFormat := conf.GetString("log.log_format") // 日期格式,如"2006-01-02" // 确保有默认的日期格式 if logFormat == "" { logFormat = "2006-01-02" } currentDate := time.Now().Format(logFormat) // 显示调试信息 fmt.Printf("[日志初始化] 服务类型: %s, 日期: %s\n", serviceTypeToString(serviceType), currentDate) if serviceType == API && conf.IsSet("log.api_log_file") { // 使用API日志路径 logPath = conf.GetString("log.api_log_file") logPath = fmt.Sprintf(logPath, currentDate) // 替换日期占位符 } else if serviceType == Task && conf.IsSet("log.task_log_file") { // 使用Task日志路径 logPath = conf.GetString("log.task_log_file") logPath = fmt.Sprintf(logPath, currentDate) // 替换日期占位符 } else if conf.IsSet("log.log_file_name") { // 即使使用旧配置,也添加日期分区 logPath = conf.GetString("log.log_file_name") // 截取扩展名前的部分,添加日期,然后加上扩展名 ext := filepath.Ext(logPath) base := logPath[:len(logPath)-len(ext)] logPath = fmt.Sprintf("%s-%s%s", base, currentDate, ext) } // 处理相对路径,兼容不同的工作目录 if strings.HasPrefix(logPath, "./") { basePath := "/data/app" // 容器中的日志基础路径 if _, err := os.Stat(basePath); os.IsNotExist(err) { // 如果/data/app不存在,则使用当前目录 workDir, err := os.Getwd() if err == nil { basePath = workDir } else { basePath = "." } } // 将相对路径转换为绝对路径 logPath = strings.Replace(logPath, "./", basePath+"/", 1) } // 显示实际使用的日志路径 fmt.Printf("[日志路径] %s\n", logPath) // 确保日志目录存在 if err := ensureDirExists(logPath); err != nil { // 如果创建目录失败,回退到临时目录 fmt.Printf("Error creating log directory: %v, using default path\n", err) logPath = "./logs/app.log" ensureDirExists(logPath) } // 获取日志级别 lv := conf.GetString("log.log_level") var level zapcore.Level //debug