zap源码阅读(3)

白沙云影

zap 和 lumberjack 结合使用

本篇内容主要是结合这两个开源库使用。

package logger

import (
    "os"
    "sync"
    "time"

    "github.com/natefinch/lumberjack"
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"
)

var Log *ZapLogger

type ZapLogger struct {
    *zap.SugaredLogger
    logLevel zap.AtomicLevel
}

const defaultloglevel = zapcore.DebugLevel // 默认日志等级为debug

//设置日志
// Param:
// logPath 日志文件路径
// logLevel 日志级别 debug/info/warn/error
// maxSize 单个文件大小,MB
// maxBackups 保存的文件个数
// compress 压缩
// jsonFormat 是否输出为json格式
// shoowLine 显示代码行
// logInConsole 是否同时输出到控制台
func (l *ZapLogger) SetLogger(logLevel, logPath string, maxSizeMb, maxBackups int, jsonFormat, logInConsole bool) {
    hook := lumberjack.Logger{
        Filename:   logPath,    // 日志文件路径
        MaxSize:    maxSizeMb,  // megabytes
        MaxBackups: maxBackups, // 最多保留300个备份
        Compress:   false,      // 是否压缩 disabled by default
    }

    var syncer zapcore.WriteSyncer
    if !logInConsole && "" != logPath {
        syncer = zapcore.NewMultiWriteSyncer(zapcore.AddSync(&hook)) //lumberjack 实现了Write 接口,所以write功能由lumberjack 来做。 
    } else {
        syncer = zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout))
    }

    formatEncodeTime := func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
        enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
    }
    encoderConfig := zapcore.EncoderConfig{
        TimeKey:        "time",
        LevelKey:       "level",
        NameKey:        "logger",
        CallerKey:      "line",
        MessageKey:     "msg",
        StacktraceKey:  "stacktrace",
        LineEnding:     zapcore.DefaultLineEnding,
        EncodeLevel:    zapcore.LowercaseLevelEncoder, 
        EncodeTime:     formatEncodeTime,
        EncodeDuration: zapcore.SecondsDurationEncoder, 
        EncodeCaller:   zapcore.ShortCallerEncoder,    
        EncodeName:     zapcore.FullNameEncoder,
    }

    var encoder zapcore.Encoder
    if jsonFormat {
        encoder = zapcore.NewJSONEncoder(encoderConfig)
    } else {
        encoder = zapcore.NewConsoleEncoder(encoderConfig)
    }

    // debug->info->warn->error
    var level zapcore.Level
    if level.UnmarshalText([]byte(logLevel)) != nil {
        level = defaultloglevel
    }

    atomicLevel := zap.NewAtomicLevelAt(level)

    core := zapcore.NewCore(
        encoder,
        syncer,
        atomicLevel,
    )

    logger := zap.New(core)
    logger = logger.WithOptions(zap.AddCaller()) //添加代码行号
    l.SugaredLogger = logger.Sugar()
    l.logLevel = atomicLevel
}

var loggers sync.Map

func GetLogger(name string) *ZapLogger {
    val, ok := loggers.Load(name)
    if ok {
        log, ok := val.(*ZapLogger)
        if !ok {
            return nil
        }
        return log
    }

    log := &ZapLogger{}

    if "" != name {
        log.SetLogger(
            "DEBUG",
            "test_"+name+".log",
            40,
            100,
            false,
            false,
        )
    } else { //输出到控制台
        log.SetLogger(
            "DEBUG",
            "",
            40,
            100,
            false,
            true,
        )
    }

    loggers.Store(name, log)
    return log
}
阅读 182
1 声望
1 粉丝
0 条评论
你知道吗?

1 声望
1 粉丝
宣传栏