forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
64 lines (56 loc) · 1.17 KB
/
stack.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
package sysutil
import (
"runtime"
"strconv"
)
// CallerInfo struct
type CallerInfo struct {
PC uintptr
Fc *runtime.Func
File string
Line int
}
// String convert
func (ci *CallerInfo) String() string {
return ci.File + ":" + strconv.Itoa(ci.Line)
}
// CallersInfos returns an array of the CallerInfo.
//
// Usage:
//
// cs := sysutil.CallersInfos(3, 2)
// for _, ci := range cs {
// fc := runtime.FuncForPC(pc)
// // maybe need check fc = nil
// fnName = fc.Name()
// }
func CallersInfos(skip, num int, filters ...func(file string, fc *runtime.Func) bool) []*CallerInfo {
filterLn := len(filters)
callers := make([]*CallerInfo, 0, num)
for i := skip; i < skip+num; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
// The breaks below failed to terminate the loop, and we ran off the
// end of the call stack.
break
}
fc := runtime.FuncForPC(pc)
if fc == nil {
continue
}
if filterLn > 0 && filters[0] != nil {
// filter - return false for skip
if !filters[0](file, fc) {
continue
}
}
// collecting
callers = append(callers, &CallerInfo{
PC: pc,
Fc: fc,
File: file,
Line: line,
})
}
return callers
}