/
caller.go
63 lines (53 loc) · 1.14 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
// Package caller provides packaging for system runtime.Caller
package caller
import (
"fmt"
"runtime"
)
// Caller identifies a caller
type Caller struct {
File File `json:"file"`
Func Function `json:"function"`
Line int `json:"line"`
}
// String implements fmt.Stringer
func (c Caller) String() string {
return fmt.Sprintf("%s, %s(), Line %d", c.File, c.Func, c.Line)
}
// GetCaller get last caller. If skip is set to 0, will get yourself.
func GetCaller(skip int) Caller {
pcs := make([]uintptr, 128)
depth := runtime.Callers(skip+2, pcs)
ca := runtime.CallersFrames(pcs[:depth])
fr, more := ca.Next()
if !more {
return Caller{
File: "",
Func: "",
Line: -1,
}
}
return Caller{
File: File(fr.File),
Func: Function(fr.Function),
Line: fr.Line,
}
}
// GetAllCallers get all caller infos
func GetAllCallers() (callers []Caller) {
pcs := make([]uintptr, 256)
depth := runtime.Callers(1, pcs)
ca := runtime.CallersFrames(pcs[:depth])
for {
fr, more := ca.Next()
callers = append(callers, Caller{
File: File(fr.File),
Func: Function(fr.Function),
Line: fr.Line,
})
if !more {
break
}
}
return
}