-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloghook.go
More file actions
115 lines (98 loc) · 2.24 KB
/
loghook.go
File metadata and controls
115 lines (98 loc) · 2.24 KB
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package logtool
import (
"fmt"
"github.com/sirupsen/logrus"
"runtime"
)
var formatter logrus.Formatter
type LoggerWrapper struct {
oldFormatter logrus.Formatter
hook *Hook
}
func (w *LoggerWrapper) Format(entry *logrus.Entry) ([]byte, error) {
modified := entry.WithField(w.hook.Field, w.hook.Formatter(w.hook.findCaller()))
modified.Level = entry.Level
modified.Message = entry.Message
return w.oldFormatter.Format(modified)
}
func newFormatter(old logrus.Formatter, hook *Hook) logrus.Formatter {
return &LoggerWrapper{oldFormatter: old, hook: hook}
}
type Hook struct {
Field string
Skip int
levels []logrus.Level
//SkipPrefixes []string
Formatter func(file, function string, line int) string
}
func (hook *Hook) Levels() []logrus.Level {
return hook.levels
}
func (hook *Hook) Fire(entry *logrus.Entry) error {
if formatter != entry.Logger.Formatter {
formatter = newFormatter(entry.Logger.Formatter, hook)
}
entry.Logger.Formatter = formatter
return nil
}
func (hook *Hook) findCaller() (string, string, int) {
var (
pc uintptr
file string
function string
line int
)
pc, file, line = getCaller(hook.Skip)
/*for i := 0; i < 10; i++ {
pc, file, line = getCaller(hook.Skip + i)
if !hook.skipFile(file) {
break
}
}*/
if pc != 0 {
frames := runtime.CallersFrames([]uintptr{pc})
frame, _ := frames.Next()
function = frame.Function
}
return file, function, line
}
/*func (hook *Hook) skipFile(file string) bool {
for i := range hook.SkipPrefixes {
if strings.HasPrefix(file, hook.SkipPrefixes[i]) {
return true
}
}
return false
}*/
func NewHook(levels ...logrus.Level) *Hook {
hook := Hook{
Field: "_source",
Skip: 9,
levels: levels,
//SkipPrefixes: []string{"logrus/", "logrus@"},
Formatter: func(file, function string, line int) string {
return fmt.Sprintf("%s:%d func:%s", file, line, function)
},
}
if len(hook.levels) == 0 {
hook.levels = logrus.AllLevels
}
return &hook
}
func getCaller(skip int) (uintptr, string, int) {
pc, file, line, ok := runtime.Caller(skip)
if !ok {
return 0, "", 0
}
/*n := 0
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
n++
if n >= 2 {
file = file[i+1:]
break
}
}
}*/
return pc, file, line
}