1

本文主要研究一下golang的zap的NewTee

NewTee

zap@v1.16.0/zapcore/tee.go

type multiCore []Core

func NewTee(cores ...Core) Core {
    switch len(cores) {
    case 0:
        return NewNopCore()
    case 1:
        return cores[0]
    default:
        return multiCore(cores)
    }
}
NewTee方法根据cores个数来返回不同的Core,若len(cores)为0,返回NewNopCore,若为1则返回cores[0],默认返回[]Core

multiCore

zap@v1.16.0/zapcore/tee.go

func (mc multiCore) With(fields []Field) Core {
    clone := make(multiCore, len(mc))
    for i := range mc {
        clone[i] = mc[i].With(fields)
    }
    return clone
}

func (mc multiCore) Enabled(lvl Level) bool {
    for i := range mc {
        if mc[i].Enabled(lvl) {
            return true
        }
    }
    return false
}

func (mc multiCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
    for i := range mc {
        ce = mc[i].Check(ent, ce)
    }
    return ce
}

func (mc multiCore) Write(ent Entry, fields []Field) error {
    var err error
    for i := range mc {
        err = multierr.Append(err, mc[i].Write(ent, fields))
    }
    return err
}

func (mc multiCore) Sync() error {
    var err error
    for i := range mc {
        err = multierr.Append(err, mc[i].Sync())
    }
    return err
}
multiCore提供了With、Enabled、Check、Write、Sync方法,它们都是遍历multiCore执行对应的操作

实例

func teeDemo() {
    buf := &bytes.Buffer{}
    teeCore := zapcore.NewTee(
        zapcore.NewCore(zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()), zapcore.AddSync(buf), zap.InfoLevel),
        zapcore.NewCore(zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig()), zapcore.Lock(os.Stdout), zap.InfoLevel),
    )
    logger := zap.New(teeCore)
    logger.Info("hello")
    fmt.Print(buf)
}
这里zapcore.NewTee将json及console两个core衔接在一起,创建logger,之后logger会往两个core写入数据

输出

2020-12-12T22:29:47.328+0800    INFO    hello
{"level":"info","ts":1607783387.3285708,"msg":"hello"}

小结

zapcore.NewTee方法可以把多个core衔接在一起,对应logger的操作会同时操作这些core。

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...