-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hook.go
89 lines (78 loc) · 1.4 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
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
78
79
80
81
82
83
84
85
86
87
88
89
package hyperlog
import (
"fmt"
"os"
"sync"
)
func MakeHookFlag(trace, debug, info, warn, error, fatal bool) int {
i := 0
if trace {
i = i | 1
}
if debug {
i = i | 2
}
if info {
i = i | 4
}
if warn {
i = i | 8
}
if error {
i = i | 16
}
if fatal {
i = i | 32
}
return i
}
var (
hookMutext sync.Mutex
hookMap = make(map[int][]LogHook)
logShutdownHandlers = make([]LogShutdownHandler, 0)
)
type LogHook interface {
FireHook(entry *LogEntry) error
}
func Fire(entry *LogEntry) {
hookMutext.Lock()
defer hookMutext.Unlock()
for fl, hooks := range hookMap {
if fl&entry.Level.Flag() == entry.Level.Flag() {
for _, hook := range hooks {
err := hook.FireHook(entry)
if err != nil {
_, _ = os.Stderr.WriteString(fmt.Sprintf("error while firing hook. got %s\n", err))
}
}
}
}
}
func Add(hook LogHook, flags int) {
hookMutext.Lock()
defer hookMutext.Unlock()
if flags == 0 || hook == nil {
return
}
if hooks, ok := hookMap[flags]; ok {
if hooks == nil {
hookMap[flags] = []LogHook{
hook,
}
} else {
hookMap[flags] = append(hookMap[flags], hook)
}
} else {
hookMap[flags] = []LogHook{
hook,
}
}
}
func Shutdown() {
for _, handler := range logShutdownHandlers {
handler.ShutdownLog()
}
}
func AddLogShutdownHandler(handler LogShutdownHandler) {
logShutdownHandlers = append(logShutdownHandlers, handler)
}