-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.go
88 lines (73 loc) · 1.47 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package errs
import (
"fmt"
"io"
"path"
"runtime"
"strconv"
)
func getStackTrace() StackTrace {
const (
maxDepth = 64
callerDepth = 4
)
pcs := make([]uintptr, maxDepth)
n := runtime.Callers(callerDepth, pcs)
resp := make([]StackFrame, n)
for i := 0; i < n; i++ {
resp[i] = frame(pcs[i]).toStackFrame()
}
return resp
}
type frame uintptr
func (f frame) pc() uintptr { return uintptr(f) - 1 }
func (f frame) toStackFrame() StackFrame {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return StackFrame{Func: "unknown", File: "unknown", Line: 0}
}
file, line := fn.FileLine(f.pc())
return StackFrame{
Func: fn.Name(),
File: file,
Line: line,
}
}
type StackTrace []StackFrame
func (s StackTrace) Format(state fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case state.Flag('+'):
for _, f := range s {
fmt.Fprintf(state, "\n%+v", f)
}
default:
}
default:
}
}
type StackFrame struct {
Func string `json:"func"`
File string `json:"file"`
Line int `json:"line"`
}
func (f StackFrame) Format(state fmt.State, verb rune) {
switch verb {
case 's':
switch {
case state.Flag('+'):
_, _ = io.WriteString(state, f.Func)
_, _ = io.WriteString(state, "\n\t")
_, _ = io.WriteString(state, f.File)
default:
_, _ = io.WriteString(state, path.Base(f.File))
}
case 'd':
_, _ = io.WriteString(state, strconv.Itoa(f.Line))
case 'v':
f.Format(state, 's')
_, _ = io.WriteString(state, ":")
f.Format(state, 'd')
}
}