-
Notifications
You must be signed in to change notification settings - Fork 0
/
logevent.go
106 lines (98 loc) · 2.16 KB
/
logevent.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package log
import (
"path"
"runtime"
"strconv"
"strings"
"time"
"github.com/askasoft/pango/str"
)
// Event log event
type Event struct {
Logger Logger `json:"-"`
Level Level
Msg string
Time time.Time
File string
Line int
Func string
Trace string
}
// CallerDepth get caller filename and line number
func (le *Event) CallerDepth(depth int, trace bool) {
dep := 1
if trace {
dep = 30
}
rpc := make([]uintptr, dep)
n := runtime.Callers(depth, rpc)
if n > 0 {
frames := runtime.CallersFrames(rpc)
frame, next := frames.Next()
_, le.Func = path.Split(frame.Function)
_, le.File = path.Split(frame.File)
le.Line = frame.Line
if next {
var sb strings.Builder
for ; next; frame, next = frames.Next() {
sb.WriteString(frame.File)
sb.WriteString(":")
sb.WriteString(strconv.Itoa(frame.Line))
sb.WriteString(" ")
sb.WriteString(frame.Function)
sb.WriteString("()")
sb.WriteString(EOL)
}
le.Trace = sb.String()
}
}
}
// CallerStop get caller filename and line number
func (le *Event) CallerStop(stop string, trace bool) {
rpc := make([]uintptr, 30)
n := runtime.Callers(2, rpc)
if n > 0 {
found := false
frames := runtime.CallersFrames(rpc)
for frame, next := frames.Next(); next; frame, next = frames.Next() {
if str.Contains(frame.File, stop) {
found = true
continue
}
if found {
_, le.Func = path.Split(frame.Function)
_, le.File = path.Split(frame.File)
le.Line = frame.Line
if trace && next {
var sb strings.Builder
for ; next; frame, next = frames.Next() {
sb.WriteString(frame.File)
sb.WriteString(":")
sb.WriteString(strconv.Itoa(frame.Line))
sb.WriteString(" ")
sb.WriteString(frame.Function)
sb.WriteString("()")
sb.WriteString(EOL)
}
le.Trace = sb.String()
}
break
}
}
}
}
func newEvent(logger Logger, lvl Level, msg string) *Event {
le := &Event{
Logger: logger,
Level: lvl,
Msg: msg,
Time: time.Now(),
File: "???",
Func: "???",
Line: 0,
}
if logger.GetCallerDepth() > 0 {
le.CallerDepth(logger.GetCallerDepth(), logger.GetTraceLevel() >= lvl)
}
return le
}