-
Notifications
You must be signed in to change notification settings - Fork 3
/
caller.go
73 lines (61 loc) · 1.43 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
64
65
66
67
68
69
70
71
72
73
package funcKit
import (
"fmt"
"runtime"
"strings"
)
// AddEntireCaller
/*
@param skip 1: 加上 调用此函数的函数的EntireCaller
e.g. main()调用此函数
(1, "123") => "test/test1.go:11|main 123"
*/
func AddEntireCaller(skip int, text string) string {
return GetEntireCaller(skip+1) + " " + text
}
// GetEntireCaller
/*
e.g.
(1) => test/test1.go:26|testFunc
*/
func GetEntireCaller(callDepth int) string {
pc, file, line, ok := runtime.Caller(callDepth)
if !ok {
return ""
}
return fmt.Sprintf("%s|%s", prettyCaller(file, line), prettyFuncName(pc))
}
// GetCaller
/*
参考: go-zero中的logx/util.go.
@param callDepth 必须满足: >=0,实际使用中: >=1
e.g.
(1) => "test/test1.go:27"
*/
func GetCaller(callDepth int) string {
_, file, line, ok := runtime.Caller(callDepth)
if !ok {
return ""
}
return prettyCaller(file, line)
}
func prettyCaller(file string, line int) string {
idx := strings.LastIndexByte(file, '/')
if idx < 0 {
return fmt.Sprintf("%s:%d", file, line)
}
idx = strings.LastIndexByte(file[:idx], '/')
if idx < 0 {
return fmt.Sprintf("%s:%d", file, line)
}
return fmt.Sprintf("%s:%d", file[idx+1:], line)
}
func prettyFuncName(pc uintptr) string {
// e.g."github.com/richelieu-yang/chimera/v2/src/core/file/fileKit.AssertExistAndIsFile"
funcName := runtime.FuncForPC(pc).Name()
index := strings.LastIndex(funcName, ".")
if index != -1 {
funcName = funcName[index+1:]
}
return funcName
}