|
@@ -0,0 +1,101 @@
|
|
|
+package logger
|
|
|
+
|
|
|
+import (
|
|
|
+ "github.com/natefinch/lumberjack"
|
|
|
+ "go.uber.org/zap"
|
|
|
+ "go.uber.org/zap/zapcore"
|
|
|
+ "os"
|
|
|
+ "time"
|
|
|
+)
|
|
|
+
|
|
|
+// error logger
|
|
|
+var log *zap.SugaredLogger
|
|
|
+
|
|
|
+var levelMap = map[string]zapcore.Level{
|
|
|
+ "debug": zapcore.DebugLevel,
|
|
|
+ "info": zapcore.InfoLevel,
|
|
|
+ "warn": zapcore.WarnLevel,
|
|
|
+ "error": zapcore.ErrorLevel,
|
|
|
+ "panic": zapcore.PanicLevel,
|
|
|
+ "fatal": zapcore.FatalLevel,
|
|
|
+}
|
|
|
+
|
|
|
+type Config struct {
|
|
|
+ Compress bool
|
|
|
+ ConsoleStdout bool
|
|
|
+ FileStdout bool
|
|
|
+ Level string
|
|
|
+ LocalTime bool
|
|
|
+ MaxAge int
|
|
|
+ MaxBackups int
|
|
|
+ MaxSize int
|
|
|
+ Path string
|
|
|
+}
|
|
|
+
|
|
|
+func Init(conf *Config) {
|
|
|
+ var syncWriters []zapcore.WriteSyncer
|
|
|
+ level := getLoggerLevel(conf.Level)
|
|
|
+ fileConfig := &lumberjack.Logger{
|
|
|
+ Filename: conf.Path, // 日志文件名
|
|
|
+ MaxSize: conf.MaxSize, // 日志文件大小
|
|
|
+ MaxAge: conf.MaxAge, // 最长保存天数
|
|
|
+ MaxBackups: conf.MaxBackups, // 最多备份几个
|
|
|
+ LocalTime: conf.LocalTime, // 日志时间戳
|
|
|
+ Compress: conf.Compress, // 是否压缩文件,使用gzip
|
|
|
+ }
|
|
|
+ encoder := zap.NewProductionEncoderConfig()
|
|
|
+ encoder.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
|
|
|
+ enc.AppendString(t.Format("2006-01-02 15:04:05"))
|
|
|
+ }
|
|
|
+ if conf.ConsoleStdout {
|
|
|
+ syncWriters = append(syncWriters, zapcore.AddSync(os.Stdout))
|
|
|
+ }
|
|
|
+ if conf.FileStdout {
|
|
|
+ syncWriters = append(syncWriters, zapcore.AddSync(fileConfig))
|
|
|
+ }
|
|
|
+ core := zapcore.NewCore(
|
|
|
+ zapcore.NewJSONEncoder(encoder),
|
|
|
+ zapcore.NewMultiWriteSyncer(syncWriters...),
|
|
|
+ zap.NewAtomicLevelAt(level))
|
|
|
+ logger := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
|
|
|
+ log = logger.Sugar()
|
|
|
+}
|
|
|
+
|
|
|
+func getLoggerLevel(lvl string) zapcore.Level {
|
|
|
+ if level, ok := levelMap[lvl]; ok {
|
|
|
+ return level
|
|
|
+ }
|
|
|
+ return zapcore.InfoLevel
|
|
|
+}
|
|
|
+
|
|
|
+func Debug(args ...interface{}) {
|
|
|
+ log.Debug(args...)
|
|
|
+}
|
|
|
+
|
|
|
+func Info(args ...interface{}) {
|
|
|
+ log.Info(args...)
|
|
|
+}
|
|
|
+
|
|
|
+func Infof(format string, args ...interface{}) {
|
|
|
+ log.Infof(format, args...)
|
|
|
+}
|
|
|
+
|
|
|
+func Warn(args ...interface{}) {
|
|
|
+ log.Warn(args...)
|
|
|
+}
|
|
|
+
|
|
|
+func Error(args ...interface{}) {
|
|
|
+ log.Error(args...)
|
|
|
+}
|
|
|
+
|
|
|
+func DPanic(args ...interface{}) {
|
|
|
+ log.DPanic(args...)
|
|
|
+}
|
|
|
+
|
|
|
+func Panic(args ...interface{}) {
|
|
|
+ log.Panic(args...)
|
|
|
+}
|
|
|
+
|
|
|
+func Fatal(args ...interface{}) {
|
|
|
+ log.Fatal(args...)
|
|
|
+}
|