序
本文主要研究一下golang的zap的NewTee
NewTee
zap@v1.16.0/zapcore/tee.go
代码语言:javascript复制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
代码语言:javascript复制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执行对应的操作
实例
代码语言:javascript复制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写入数据
输出
代码语言:javascript复制2020-12-12T22:29:47.328 0800 INFO hello
{"level":"info","ts":1607783387.3285708,"msg":"hello"}
小结
zapcore.NewTee方法可以把多个core衔接在一起,对应logger的操作会同时操作这些core。
doc
- zap