实现方式

Overview

Hook - 图1
hooked 通过匿名包含 zapcore.Core 实例,直接满足 zapcore.Core 接口。通过覆盖特定方法,实现 hook 方法写日志的功能。

结构与注册

hooked 定义

  1. type hooked struct {
  2. Core // 匿名包含,直接实现接口方法的继承
  3. funcs []func(Entry) error
  4. }

hook 注册

  1. func RegisterHooks(core Core, hooks ...func(Entry) error) Core {
  2. funcs := append([]func(Entry) error{}, hooks...) // 直接创建 hook 切片,并追加
  3. return &hooked{
  4. Core: core,
  5. funcs: funcs,
  6. }
  7. }

复写关键方法

With

  1. func (h *hooked) With(fields []Field) Core {
  2. return &hooked{
  3. Core: h.Core.With(fields), // 代理
  4. funcs: h.funcs,
  5. }
  6. }

Check

  1. func (h *hooked) Check(ent Entry, ce *CheckedEntry) *CheckedEntry {
  2. // Let the wrapped Core decide whether to log this message or not. This
  3. // also gives the downstream a chance to register itself directly with the
  4. // CheckedEntry.
  5. if downstream := h.Core.Check(ent, ce); downstream != nil {
  6. return downstream.AddCore(ent, h)
  7. }
  8. return ce
  9. }

Write

  1. func (h *hooked) Write(ent Entry, _ []Field) error {
  2. // Since our downstream had a chance to register itself directly with the
  3. // CheckedMessage, we don't need to call it here.
  4. var err error
  5. for i := range h.funcs {
  6. err = multierr.Append(err, h.funcs[i](ent))
  7. }
  8. return err
  9. }