package log
import (
"NOONASN/global"
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"os"
"path"
"path/filepath"
)
func GetLogger(name string) *zap.Logger {
logPath := global.Cfg.Logger.LogPath
if !path.IsAbs(logPath) {
if absLogPath, err := filepath.Abs(logPath); err == nil {
logPath = absLogPath
}
}
debug := global.Cfg.Logger.Debug
hook := lumberjack.Logger{
Filename: logPath, // 日志文件路径
MaxSize: 128, // 每个日志文件保存的大小 单位:M
MaxAge: 7, // 文件最多保存多少天
MaxBackups: 30, // 日志文件最多保存多少个备份
Compress: false, // 是否压缩
}
encoderConfig := zapcore.EncoderConfig{
MessageKey: "msg",
LevelKey: "level",
TimeKey: "time",
NameKey: "logger",
CallerKey: "file",
StacktraceKey: "stacktrace",
LineEnding: zapcore.DefaultLineEnding,
EncodeLevel: zapcore.LowercaseLevelEncoder,
EncodeTime: zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05"),
EncodeDuration: zapcore.SecondsDurationEncoder,
EncodeCaller: zapcore.ShortCallerEncoder, // 短路径编码器
EncodeName: zapcore.FullNameEncoder,
}
// 设置日志级别
atomicLevel := zap.NewAtomicLevel()
atomicLevel.SetLevel(zap.DebugLevel)
var writes = []zapcore.WriteSyncer{zapcore.AddSync(&hook)}
// 如果是开发环境,同时在控制台上也输出
if debug {
writes = append(writes, zapcore.AddSync(os.Stdout))
}
core := zapcore.NewCore(
zapcore.NewJSONEncoder(encoderConfig), // json格式的日志
//zapcore.NewConsoleEncoder(encoderConfig), // 文子形式的日志
zapcore.NewMultiWriteSyncer(writes...),
atomicLevel,
)
// 开启开发模式,堆栈跟踪
caller := zap.AddCaller()
// 开启文件及行号
development := zap.Development()
// 设置初始化字段
field := zap.Fields(zap.String("appName", name))
// 构造日志
return zap.New(core, caller, development, field)
}
标签:zapcore,writes,logPath,golang,日志,Logger,zap
From: https://www.cnblogs.com/wtil/p/17154358.html