-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrace.go
73 lines (61 loc) · 1.35 KB
/
trace.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
package trace
import (
"bytes"
"fmt"
"io"
"runtime"
)
// Output flags
const (
Lfile = 1 << iota // full file name
Lline // line number
Lfunction // name of the function
LstdFlags = Lfile | Lfunction // initial values
)
// Here returns string representation of a reference
// default flags LstdFlags
func Here(flags int) string {
return FromParent(1, flags)
}
// FromParent returns string representation of a parent reference
// default flags LstdFlags
func FromParent(calldepth int, flags int) string {
var buf bytes.Buffer
frame := getFrame(calldepth + 2)
outputFrame(flags, frame, &buf)
return buf.String()
}
func outputFrame(flags int, frame *runtime.Frame, w io.Writer) {
if flags == 0 {
flags = LstdFlags
}
if frame != nil {
if flags&Lfile != 0 {
fmt.Fprintf(w, "%s", frame.File)
}
if flags&Lline != 0 {
fmt.Fprintf(w, ":%d", frame.Line)
}
if flags&Lfunction != 0 {
fmt.Fprintf(w, " %s", frame.Function)
}
}
}
func getFrame(calldepth int) *runtime.Frame {
pc, file, line, ok := runtime.Caller(calldepth)
if !ok {
return nil
}
frame := &runtime.Frame{
PC: pc,
File: file,
Line: line,
}
funcForPc := runtime.FuncForPC(pc)
if funcForPc != nil {
frame.Func = funcForPc
frame.Function = funcForPc.Name()
frame.Entry = funcForPc.Entry()
}
return frame
}