-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathstacktrace.go
47 lines (39 loc) · 1 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
package di
import (
"fmt"
"runtime"
"strings"
)
// stacktrace returns stacktrace call frame with skip.
func stacktrace(skip int) (frame callerFrame) {
pc, file, line, ok := runtime.Caller(skip + 2)
if !ok {
return callerFrame{}
}
f := runtime.FuncForPC(pc)
return callerFrame{
function: shortFuncName(f),
file: file,
line: line,
}
}
// callerFrame represents stacktrace frame.
type callerFrame struct {
function string
file string
line int
}
// Format formats stacktrace frame.
func (f callerFrame) Format(s fmt.State, c rune) {
_, _ = fmt.Fprintf(s, "%s:%d", f.file, f.line)
}
func shortFuncName(f *runtime.Func) string {
longName := f.Name()
withoutPath := longName[strings.LastIndex(longName, "/")+1:]
withoutPackage := withoutPath[strings.Index(withoutPath, ".")+1:]
shortName := withoutPackage
shortName = strings.Replace(shortName, "(", "", 1)
shortName = strings.Replace(shortName, "*", "", 1)
shortName = strings.Replace(shortName, ")", "", 1)
return shortName
}