forked from Meituan-Dianping/cat-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stacktrace.go
58 lines (52 loc) · 1.12 KB
/
stacktrace.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
package cat
import (
"bytes"
"fmt"
"go/build"
"path/filepath"
"runtime"
"strings"
)
var trimPaths []string
func init() {
for _, prefix := range build.Default.SrcDirs() {
if prefix[len(prefix)-1] != filepath.Separator {
prefix += string(filepath.Separator)
}
trimPaths = append(trimPaths, prefix)
}
}
func trimPath(filename string) string {
for _, prefix := range trimPaths {
if trimmed := strings.TrimPrefix(filename, prefix); len(trimmed) < len(filename) {
return trimmed
}
}
return filename
}
func functionName(pc uintptr) string {
fn := runtime.FuncForPC(pc)
if fn == nil {
return "unknown"
}
return fn.Name()
}
func NewStacktrace(skip int, err error) (buf *bytes.Buffer) {
buf = bytes.NewBuffer([]byte{})
buf.WriteString(err.Error())
buf.WriteRune('\n')
for i := skip; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
file = trimPath(file)
name := functionName(pc)
// `runtime.goexit` is bootstrap loader and is meaningless in tracing.
if name == "runtime.goexit" {
continue
}
buf.WriteString(fmt.Sprintf("at %s(%s:%d)\n", name, file, line))
}
return buf
}