-
Notifications
You must be signed in to change notification settings - Fork 0
/
zapmixin.go
77 lines (63 loc) · 1.47 KB
/
zapmixin.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package zapmixin
import (
"github.com/fox-one/mixin-sdk-go"
"go.uber.org/zap/zapcore"
)
type Handler struct {
conversations []string
client MixinClient
levels []zapcore.Level
async bool
formatter func(zapcore.Entry) string
filter func(zapcore.Entry) bool
afterFunc func(zapcore.Entry, *mixin.MessageRequest, error) error
}
func New(client *mixin.Client, conversations []string, opts ...Option) (*Handler, error) {
return newHandler(client, conversations, opts...)
}
func newHandler(client MixinClient, conversations []string, opts ...Option) (*Handler, error) {
h := &Handler{
client: client,
conversations: conversations,
levels: getLevelThreshold(zapcore.WarnLevel),
async: true,
}
if err := h.Apply(opts...); err != nil {
return nil, err
}
return h, nil
}
func (h *Handler) Apply(opts ...Option) error {
for _, opt := range opts {
if err := opt(h); err != nil {
return err
}
}
return nil
}
func (h *Handler) Client() *mixin.Client {
return h.client.(*mixin.Client)
}
func (h *Handler) Hook() func(zapcore.Entry) error {
return func(e zapcore.Entry) error {
if !h.levelMatched(e.Level) {
return nil
}
if h.filter != nil && !h.filter(e) {
return nil
}
if h.async {
go h.sendMessage(e)
return nil
}
return h.sendMessage(e)
}
}
func (h *Handler) levelMatched(l zapcore.Level) bool {
for _, level := range h.levels {
if level == l {
return true
}
}
return false
}