You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.5 KiB
62 lines
2.5 KiB
package util
|
|
|
|
import (
|
|
"fmt"
|
|
"path/filepath"
|
|
"time"
|
|
|
|
"go.uber.org/zap"
|
|
"go.uber.org/zap/zapcore"
|
|
)
|
|
|
|
var logger *zap.Logger
|
|
|
|
func initZapLogger() {
|
|
// Initialize Zap Logger
|
|
var err error
|
|
config := zap.NewDevelopmentConfig() // For development, human-readable output
|
|
// For production, use zap.NewProductionConfig() for structured, high-performance logging
|
|
// config := zap.NewProductionConfig()
|
|
|
|
// ------------------------------------
|
|
|
|
// --- 关键修改:配置日志输出路径 ---
|
|
// 1. 设置主日志输出路径。这里指向一个文件。
|
|
config.OutputPaths = []string{"logs/app.log", "stdout"} // 输出到 logs/app.log 和控制台
|
|
// 如果只想输出到文件,可以只写 "logs/app.log"
|
|
// config.OutputPaths = []string{"logs/app.log"}
|
|
|
|
// 2. 设置错误日志输出路径 (通常也指向文件,或者 stderr)
|
|
config.ErrorOutputPaths = []string{"logs/app-errors.log", "stderr"} // 错误日志到单独文件和控制台
|
|
// 或者指向与主日志相同的文件: config.ErrorOutputPaths = []string{"logs/app.log", "stderr"}
|
|
|
|
// ------------------------------------
|
|
|
|
// **关键:自定义 EncodeTime 函数**
|
|
// config.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder // ISO8601 time format,示例 2025-05-27T14:17:13.089+0800
|
|
config.EncoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
|
|
// 使用你想要的 Go 时间布局字符串来格式化时间
|
|
enc.AppendString(t.Format("2006-01-02 15:04:05.000")) // 精确到毫秒
|
|
// 如果只想要秒,可以用 t.Format("2006-01-02 15:04:05")
|
|
}
|
|
|
|
// Customize the encoder config for more readable development logs
|
|
config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder // Colored log levels
|
|
config.EncoderConfig.EncodeCaller = zapcore.ShortCallerEncoder // Short caller info
|
|
config.EncoderConfig.EncodeCaller = func(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder) {
|
|
// caller.FullPath() 返回完整的路径,例如 "your_module_name/package/file.go:line"
|
|
// caller.TrimmedPath() 返回模块路径后的相对路径,例如 "package/file.go:line"
|
|
|
|
// 我们可以使用 filepath.Base 来获取文件名(带扩展名)
|
|
// 然后拼接行号
|
|
fileName := filepath.Base(caller.File)
|
|
// 构建 "文件名:行号" 格式
|
|
enc.AppendString(fmt.Sprintf("%s:%d", fileName, caller.Line))
|
|
}
|
|
|
|
logger, err = config.Build()
|
|
if err != nil {
|
|
panic(fmt.Sprintf("Failed to initialize logger: %v", err))
|
|
}
|
|
defer logger.Sync() // Flushes buffer, if any
|
|
}
|
|
|