In the Go language, you can runtime
obtain the caller information through the Caller function in the package.
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
- skip indicates which layer of call stack information to view, where 0 indicates the currently called
Caller
function. - pc program counter
- file file
- line how many lines
- ok Is it possible to obtain call stack information?
for example
package main
import (
"fmt"
"runtime"
"time"
)
func main() {
test2()
time.Sleep(2*time.Second)
}
func test2() {
test1(0)
test1(1)
go test1(1)
}
func test1(skip int) {
callerFuncName := "unknown"
pc, file, line, ok := runtime.Caller(skip)
if ok {
fn := runtime.FuncForPC(pc)
if fn != nil {
callerFuncName = fn.Name()
}
fmt.Printf("caller:%s, file:%s, line:%d\n", callerFuncName, file, line)
}
}
output
caller:main.test1, file:/Users/lanyangyang/workspace/go_example/caller.go, line:30
caller:main.test2, file:/Users/lanyangyang/workspace/go_example/caller.go, line:21
caller:runtime.goexit, file:/usr/local/go/src/runtime/asm_amd64.s, line:1581
skip 0, caller is test1
skip 1, caller is test2
skip 1, a new goroutine executes test1, and the caller isruntime.goexit