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

在Go语言中,可以使用`runtime.Caller`函数获取调用者的详细信息,包括函数名、文件和行号。示例代码展示了如何在不同skip值下获取不同层级的调用者,例如skip=0时,获取到的是`test1`函数,skip=1时则获取到`test2`。当在新goroutine中调用时,caller可能是`runtime.goexit`。
摘要由CSDN通过智能技术生成

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

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

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

举个例子

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值