-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcaller.go
69 lines (56 loc) · 1.13 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
/**
* @author lin.tan
* @date 2023/1/6
* @description
*/
package logrus_filename
import (
"runtime"
"strings"
"sync"
)
var once sync.Once
var logrusPackage string
const (
maximumCallerDepth = 25
minimumCallerDepth = 4
)
func GetCaller(skip int) *runtime.Frame {
once.Do(func() {
pcs := make([]uintptr, maximumCallerDepth)
_ = runtime.Callers(0, pcs)
for i := 0; i < maximumCallerDepth; i++ {
funcName := runtime.FuncForPC(pcs[i]).Name()
if strings.Contains(funcName, "fireHooks") {
logrusPackage = getPackageName(funcName)
break
}
}
})
pcs := make([]uintptr, maximumCallerDepth)
depth := runtime.Callers(minimumCallerDepth, pcs)
frames := runtime.CallersFrames(pcs[:depth])
for f, again := frames.Next(); again; f, again = frames.Next() {
pkg := getPackageName(f.Function)
if pkg != logrusPackage {
if skip > 0 {
skip--
continue
}
return &f
}
}
return nil
}
func getPackageName(f string) string {
for {
lastPeriod := strings.LastIndex(f, ".")
lastSlash := strings.LastIndex(f, "/")
if lastPeriod > lastSlash {
f = f[:lastPeriod]
} else {
break
}
}
return f
}