forked from zlyuancn/zlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhook.go
51 lines (46 loc) · 1.11 KB
/
hook.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
-------------------------------------------------
Author : Zhang Fan
date: 2020/4/17
Description :
-------------------------------------------------
*/
package zlog
import (
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type interceptorFunc func(ent *zapcore.Entry, fields []zapcore.Field) (cancel bool)
type interceptor struct {
zapcore.Core
funcs []interceptorFunc
}
// 拦截器
func WithHook(funcs ...interceptorFunc) zap.Option {
return zap.WrapCore(func(core zapcore.Core) zapcore.Core {
return &interceptor{
Core: core,
funcs: append(([]interceptorFunc)(nil), funcs...),
}
})
}
func (c *interceptor) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {
if c.Enabled(ent.Level) {
return ce.AddCore(ent, c)
}
return ce
}
func (h *interceptor) With(fields []zapcore.Field) zapcore.Core {
return &interceptor{
Core: h.Core.With(fields),
funcs: h.funcs,
}
}
func (c *interceptor) Write(ent zapcore.Entry, fields []zapcore.Field) error {
for i := range c.funcs {
if c.funcs[i](&ent, fields) {
return nil
}
}
return c.Core.Write(ent, fields)
}