Files
aigrammar/logger.go
2024-08-12 04:10:48 +00:00

54 lines
1.8 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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))
}