实现方式
Overview

hooked 通过匿名包含 zapcore.Core 实例,直接满足 zapcore.Core 接口。通过覆盖特定方法,实现 hook 方法写日志的功能。
结构与注册
hooked 定义
type hooked struct {Core // 匿名包含,直接实现接口方法的继承funcs []func(Entry) error}
hook 注册
func RegisterHooks(core Core, hooks ...func(Entry) error) Core {funcs := append([]func(Entry) error{}, hooks...) // 直接创建 hook 切片,并追加return &hooked{Core: core,funcs: funcs,}}
复写关键方法
With
func (h *hooked) With(fields []Field) Core {return &hooked{Core: h.Core.With(fields), // 代理funcs: h.funcs,}}
Check
func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {// Let the wrapped Core decide whether to log this message or not. This// also gives the downstream a chance to register itself directly with the// CheckedEntry.if downstream := h.Core.Check(ent, ce); downstream != nil {return downstream.AddCore(ent, h)}return ce}
Write
func (h *hooked) Write(ent Entry, _ []Field) error {// Since our downstream had a chance to register itself directly with the// CheckedMessage, we don't need to call it here.var err errorfor i := range h.funcs {err = multierr.Append(err, h.funcs[i](ent))}return err}
