-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
inforus.go
87 lines (74 loc) · 1.45 KB
/
inforus.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
package inforus
import (
"path"
"runtime"
"strings"
"sync"
log "github.com/sirupsen/logrus"
)
// Skip the following 3 frames.
// runtime.Callers
// github.com/178inaba/inforus.Hook.Fire
// github.com/178inaba/inforus.(*Hook).Fire
const skipFrameCnt = 3
// AddHookDefault is ...
func AddHookDefault() {
log.AddHook(Hook{
mu: &sync.Mutex{},
file: true,
line: true,
function: false,
levels: log.AllLevels,
})
}
// AddHook is ...
func AddHook(file, line, function bool, levels []log.Level) {
log.AddHook(Hook{
mu: &sync.Mutex{},
file: file,
line: line,
function: function,
levels: levels,
})
}
// Hook is ...
type Hook struct {
mu *sync.Mutex
file bool
line bool
function bool
levels []log.Level
}
// Levels is ...
func (h Hook) Levels() []log.Level {
return h.levels
}
// Fire is ...
func (h Hook) Fire(entry *log.Entry) error {
pc := make([]uintptr, 64)
cnt := runtime.Callers(skipFrameCnt, pc)
for i := 0; i < cnt; i++ {
fu := runtime.FuncForPC(pc[i])
name := fu.Name()
if !strings.Contains(name, "github.com/sirupsen/logrus") {
file, line := fu.FileLine(pc[i] - 1)
if h.file {
h.mu.Lock()
entry.Data["file"] = path.Base(file)
h.mu.Unlock()
}
if h.function {
h.mu.Lock()
entry.Data["func"] = path.Base(name)
h.mu.Unlock()
}
if h.line {
h.mu.Lock()
entry.Data["line"] = line
h.mu.Unlock()
}
break
}
}
return nil
}