liuxiaolong
2020-11-18 6f2e112e3f17fda619eb9c19a8d8d2ae9d9598d9
logger.go
@@ -1,6 +1,7 @@
package logger
import (
   "errors"
   "github.com/natefinch/lumberjack"
   "go.uber.org/zap"
   "go.uber.org/zap/zapcore"
@@ -13,6 +14,11 @@
   logger *zap.SugaredLogger
}
var (
   blog *BLog
   atomicLevel = zap.NewAtomicLevelAt(zapcore.DebugLevel)
)
func (l *BLog) Write(buf []byte) (n int, err error) {
   l.logger.Debug(strings.Replace(string(buf),"\n","", -1))
   return len(buf),nil
@@ -21,8 +27,6 @@
func GetLogFile() *BLog {
   return  blog
}
var blog *BLog
const (
   DebugLevel = iota -1
@@ -33,6 +37,7 @@
   PanicLevel
   FatalLevel
)
func InitLogger(logPath string, logLevel int,maxSize int, maxBackups int, maxAge int) {
   logdir := "./logger/"
   if index := strings.LastIndex(logPath, "/"); index != -1 {
@@ -52,6 +57,31 @@
   }
   w := zapcore.AddSync(&hook)
   atomicLevel = zap.NewAtomicLevelAt(getZapLevel(logLevel))
   encoderConfig := zap.NewProductionEncoderConfig()
   encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
   encoderConfig.CallerKey = "file"
   encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
   encoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
      enc.AppendString(t.Format("2006-01-02 15:04:05"))
   }
   core := zapcore.NewCore(
      zapcore.NewConsoleEncoder(encoderConfig),
      w,
      atomicLevel,
   )
   log := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
   blog = &BLog{
      logger: log.Sugar(),
   }
   blog.logger.Info("init logger success")
}
func getZapLevel(logLevel int) zapcore.Level {
   var level zapcore.Level
   switch logLevel {
   case DebugLevel:
@@ -71,24 +101,16 @@
   default:
      level = zap.InfoLevel
   }
   encoderConfig := zap.NewProductionEncoderConfig()
   encoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
   encoderConfig.CallerKey = "file"
   encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
   encoderConfig.EncodeTime = func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
      enc.AppendString(t.Format("2006-01-02 15:04:05"))
   }
   return level
}
   core := zapcore.NewCore(
      zapcore.NewConsoleEncoder(encoderConfig),
      w,
      level,
   )
   log := zap.New(core, zap.AddCaller(), zap.AddCallerSkip(1))
   blog = &BLog{
      logger: log.Sugar(),
func SetLevel(lv int) error {
   if blog !=nil && blog.logger != nil {
      atomicLevel.SetLevel(getZapLevel(lv))
      return nil
   } else {
      return errors.New("logger handle is nil")
   }
   blog.logger.Info("init logger success")
}
func Debug(v ...interface{}) {