May 8, 2024
第三方包
#
zap记录日志
#
package boot
import (
"fmt"
"path"
"time"
"github.com/xiaohubai/alpha/config"
zaprotatelogs "github.com/lestrrat-go/file-rotatelogs"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
var level zapcore.Level
// Zap 日志组件
func Zap() (logger *zap.Logger) {
level = zap.InfoLevel
logger = zap.New(getEncoderCore())
logger.WithOptions(zap.AddCaller())
return logger
}
func getEncoderCore() (core zapcore.Core) {
writer, err := GetWriteSyncer() // 使用file-rotatelogs进行日志分割
if err != nil {
panic(fmt.Errorf("Get Write Syncer Failed err:%v", err.Error()))
}
return zapcore.NewCore(zapcore.NewJSONEncoder(getEncoderConfig()), writer, level)
}
func getEncoderConfig() (cfg zapcore.EncoderConfig) {
cfg = zapcore.EncoderConfig{
MessageKey: "trace_id",
LevelKey: "level",
TimeKey: "time",
NameKey: "logger",
CallerKey: "caller",
StacktraceKey: config.CONFIG.Zap.StacktraceKey,
LineEnding: zapcore.DefaultLineEnding, //默认换行
EncodeLevel: zapcore.LowercaseLevelEncoder, //小写
EncodeTime: CustomTimeEncoder, //输出时间
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.FullCallerEncoder, //记录调用路径
}
return cfg
}
// 自定义日志输出时间格式
func CustomTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}
// GetWriteSyncer 日志分割
func GetWriteSyncer() (zapcore.WriteSyncer, error) {
fileWriter, err := zaprotatelogs.New(
path.Join(config.CONFIG.Zap.Director, "%Y-%m-%d.log"),
zaprotatelogs.WithLinkName(config.CONFIG.Zap.LinkName),
zaprotatelogs.WithMaxAge(30*24*time.Hour), //日志清除时间
zaprotatelogs.WithRotationTime(24*time.Hour), //日志文件创建时间
)
return zapcore.AddSync(fileWriter), err
}