-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcaller.go
87 lines (80 loc) · 1.54 KB
/
caller.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 bilog
import (
"runtime"
"sync"
_ "unsafe"
)
const (
defaultCallDepth = 3
defaultFile = "???"
)
var (
cache = make(map[uintptr]runtime.Frame, 16)
concurrentCache sync.Map
)
// Caller 输出调用函数的文件名和行号
func Caller(callDepth int) (file string, line int) {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
file = defaultFile
} else {
file = cutFileName(file)
}
return
}
func CallerOfCache(skip int) (file string, line int) {
rpc := make([]uintptr, 1)
n := runtime.Callers(skip+1, rpc[:])
if n < 1 {
return
}
if frame, ok := cache[rpc[0]]; ok {
file = frame.File
line = frame.Line
} else {
frame, _ = runtime.CallersFrames(rpc).Next()
cache[rpc[0]] = frame
file = frame.File
line = frame.Line
}
file = cutFileName(file)
return
}
func CallerOfConcurrentCache(skip int) (file string, line int) {
rpc := make([]uintptr, 1)
n := runtime.Callers(skip+1, rpc[:])
if n < 1 {
return
}
frameI, ok := concurrentCache.Load(rpc[0])
if ok {
file = frameI.(runtime.Frame).File
line = frameI.(runtime.Frame).Line
} else {
frame, _ := runtime.CallersFrames(rpc).Next()
concurrentCache.Store(rpc[0], frame)
file = frame.File
line = frame.Line
}
file = cutFileName(file)
return
}
func cutFileName(file string) string {
switch file {
case "", defaultFile:
return defaultFile
}
var split int
var match int
for i := len(file) - 1; i >= 0; i-- {
if match == 2 {
split = i + 2
break
}
switch file[i] {
case '/', '\\':
match++
}
}
return file[split:]
}