序
本文次要钻研一下 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
- zap