zapstd.go 2.21 KB
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
package logz

import (
	"github.com/go-kratos/kratos/v2/log"
	"github.com/spf13/cast"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

var (
	_ log.Logger = &zapStd{}

	// kratos映射zap的level
	levelMap = map[log.Level]zapcore.Level{
		log.LevelDebug: zapcore.DebugLevel,
		log.LevelInfo:  zapcore.InfoLevel,
		log.LevelWarn:  zapcore.WarnLevel,
		log.LevelError: zapcore.ErrorLevel,
		log.LevelFatal: zapcore.FatalLevel,
	}
	// DefaultConfig 默认配置
	DefaultConfig = &Config{
		Color: true,
		Level: "DEBUG",
	}
)

type (
	zapStd struct {
		log *zap.SugaredLogger
	}

	Config struct {
		Color bool
		Level string
	}
)

func NewLogger(conf *Config, option ...zap.Option) *zapStd {
	if conf == nil {
		conf = DefaultConfig
	}
	var level zapcore.Level
	if v, ok := levelMap[log.ParseLevel(conf.Level)]; ok {
		level = v
	} else {
		level = zapcore.InfoLevel
	}

	cfg := zap.NewProductionEncoderConfig()
	if conf.Color {
		// 颜色
		cfg.EncodeLevel = zapcore.CapitalColorLevelEncoder
	} else {
		cfg.EncodeLevel = zapcore.CapitalLevelEncoder
	}

	cfg.ConsoleSeparator = "  |  "

	// 指定日志时间格式
	cfg.EncodeTime = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000")
	//cfg.EncodeCaller = zapcore.FullCallerEncoder

	// 使用控制台输出
	encoder := zapcore.NewConsoleEncoder(cfg)
	core := zapcore.NewCore(encoder, zapcore.AddSync(os.Stdout), level)
	l := zap.New(zapcore.NewTee(core), option...)

	zapStdLog := &zapStd{
		log: l.Sugar(),
	}
	return zapStdLog
}

func (z *zapStd) Log(level log.Level, keyvals ...interface{}) error {
	if len(keyvals) == 0 {
		return nil
	}
	if (len(keyvals) & 1) == 1 {
		keyvals = append(keyvals, "key val params invalid")
	}

	var msg string
	kv := make([]interface{}, 0, len(keyvals))

	for i := 0; i < len(keyvals); i += 2 {
		if keyvals[i] == log.DefaultMessageKey {
			msg = cast.ToString(keyvals[i+1])
			continue
		}
		kv = append(kv, keyvals[i], keyvals[i+1])
	}

	switch level {
	case log.LevelDebug:
		z.log.Debugw(msg, kv...)
	case log.LevelInfo:
		z.log.Infow(msg, kv...)
	case log.LevelWarn:
		z.log.Warnw(msg, kv...)
	case log.LevelError:
		z.log.Errorw(msg, kv...)
	case log.LevelFatal:
		z.log.Fatalw(msg, keyvals)
	}

	return nil
}

func (z *zapStd) Flush() {
	z.log.Sync()
}