-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlocation.go
More file actions
32 lines (25 loc) · 809 Bytes
/
location.go
File metadata and controls
32 lines (25 loc) · 809 Bytes
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
package errorx
import (
"fmt"
"path"
"runtime"
"strings"
)
func getLocation() string {
// 0 for the current function, 1 for the caller, and 2 for the caller of the caller
// returned file is absolute path, e.g.: /home/ericuni/git/errorx/error_test.go
pc, file, line, _ := runtime.Caller(2)
fun := runtime.FuncForPC(pc)
fileName := path.Base(file)
// fun.Name() is like
// github.com/ericuni/errorx.TestNew
// github.com/ericuni/errorx.TestTrace.func2.1 if has goroutine or subtest
fullFunName := fun.Name()
parts := strings.Split(path.Base(fullFunName), ".")
if len(parts) < 2 {
return fmt.Sprintf("[%s.%s:%d]", fullFunName, fileName, line)
}
pkg := path.Join(path.Dir(fullFunName), parts[0])
funName := parts[1]
return fmt.Sprintf("[%s/%s:%s:%d]", pkg, fileName, funName, line)
}