关于golang:zap源码阅读3

39次阅读

共计 2173 个字符,预计需要花费 6 分钟才能阅读完成。

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

正文完
 0