如何在Go的函数中得到调用者函数名(caller)

发布时间 2023-03-28 21:10:35作者: 翔云123456

在go语言中,可以通过runtimepackage中 Caller函数获取调用者信息

func Caller(skip int) (pc uintptr, file string, line int, ok bool)

  • skip 表示查看第几层调用栈信息,其中0表示的就是当前调用Caller的函数
  • pc program counter
  • file 文件
  • line 多少行
  • ok 是否可以获取调用栈信息

举个例子

 lanyangyang@YangdeMacBook-Pro  ~/workspace/go_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就是test1
skip 1, caller就是test2

skip 1, 一个新goroutine执行 test1,caller就是 runtime.goexit

参考

runtime