runtime包中有一个函数func Caller(skip int) (pc uintptr, file string, line int, ok bool)
,可以用来获得在当前运行的goroutine栈上的函数调用信息(go文件名和行号)。
参数skip表示要回溯的栈帧,例如:
main() // skip = 3
|- foo() // skip = 2
|- bar() // skip = 1
| - runtime.Caller() // skip = 0
下面的代码打印出完整的调用栈信息:
package main
import (
"fmt"
"runtime"
)
func main() {
foo()
}
func foo() {
bar()
}
func bar() {
fmt.Println(getCallers())
}
func getCallers() string {
callers := ""
for i := 0; true; i++ {
_, file, line, ok := runtime.Caller(i)
if !ok {
break
}
callers = callers + fmt.Sprintf("%v:%v\n", file, line)
}
return callers
}
输出:
/mygo/src/main.go:20
/mygo/src/main.go:15
/mygo/src/main.go:12
/mygo/src/main.go:9
/usr/local/Cellar/go/1.11/libexec/src/runtime/proc.go:201
/usr/local/Cellar/go/1.11/libexec/src/runtime/asm_amd64.s:1333