54 lines
1.8 KiB
Go
54 lines
1.8 KiB
Go
package main
|
||
|
||
import (
|
||
"github.com/natefinch/lumberjack"
|
||
"go.uber.org/zap"
|
||
"go.uber.org/zap/zapcore"
|
||
)
|
||
|
||
// Logger 是全局日志器
|
||
var logger *zap.Logger
|
||
|
||
func initLogger(filename string, maxsize int, maxbackups int, maxage int, compress bool, level string) {
|
||
// 日志文件切割配置
|
||
logWriter := zapcore.AddSync(&lumberjack.Logger{
|
||
Filename: filename, // 日志文件位置
|
||
MaxSize: maxsize, // 每个日志文件保存的最大尺寸 单位:M
|
||
MaxBackups: maxbackups, // 日志文件最多保存多少个备份
|
||
MaxAge: maxage, // 文件最多保存多少天
|
||
Compress: compress, // 是否压缩
|
||
})
|
||
|
||
// 编码器配置
|
||
encoderConfig := zapcore.EncoderConfig{
|
||
TimeKey: "time",
|
||
LevelKey: "level",
|
||
NameKey: "logger",
|
||
CallerKey: "caller",
|
||
FunctionKey: "func",
|
||
MessageKey: "msg",
|
||
StacktraceKey: "stacktrace",
|
||
LineEnding: zapcore.DefaultLineEnding,
|
||
EncodeLevel: zapcore.LowercaseLevelEncoder, // 小写编码器
|
||
EncodeTime: zapcore.ISO8601TimeEncoder, // ISO8601 UTC 时间格式
|
||
EncodeDuration: zapcore.SecondsDurationEncoder,
|
||
EncodeCaller: zapcore.ShortCallerEncoder, // 短路径编码器
|
||
}
|
||
|
||
// 设置日志级别
|
||
// UnmarshalText unmarshals the text to an AtomicLevel. It uses the same text representations as the static
|
||
// zapcore.Levels ("debug", "info", "warn", "error", "dpanic", "panic", and "fatal").
|
||
atomicLevel := zap.NewAtomicLevel()
|
||
atomicLevel.UnmarshalText([]byte(level))
|
||
//atomicLevel.SetLevel(zap.InfoLevel)
|
||
|
||
core := zapcore.NewCore(
|
||
zapcore.NewJSONEncoder(encoderConfig), // 编码器配置
|
||
logWriter, // 日志写入器
|
||
atomicLevel, // 日志级别
|
||
)
|
||
|
||
// 初始化日志器
|
||
logger = zap.New(core, zap.AddCaller(), zap.AddStacktrace(zap.ErrorLevel))
|
||
}
|