美文网首页Golang 入门资料+笔记
golang获取调用者的方法名及所在源码行数

golang获取调用者的方法名及所在源码行数

作者: 五岁小孩 | 来源:发表于2021-02-28 11:19 被阅读0次

golang获取调用者的方法名及所在源码行数

  • 代码如下

    参数:skip是要提升的堆栈帧数,0-当前函数,1-上一层函数,....

    返回值:

    pc是uintptr这个返回的是函数指针

    file是函数所在文件名目录

    line所在行号

    ok 是否可以获取到信息

      pc0, file0, line0, ok0 := runtime.Caller(0)
      logs.Error(" runtime.Caller(0) pc0:",pc0)
      logs.Error(" runtime.Caller(0) file0:",file0)
      logs.Error(" runtime.Caller(0) line0:",line0)
      logs.Error(" runtime.Caller(0) ok0:",ok0)
      f0 := runtime.FuncForPC(pc0)
      logs.Error(" runtime.FuncForPC(pc0):",f0.Name())
      pc1, file1, line1, ok1 := runtime.Caller(1)
      logs.Error(" runtime.Caller(1) pc1:",pc1)
      logs.Error(" runtime.Caller(1) file1:",file1)
      logs.Error(" runtime.Caller(1) line1:",line1)
      logs.Error(" runtime.Caller(1) ok1:",ok1)
      f1 := runtime.FuncForPC(pc1)
      logs.Error(" runtime.FuncForPC(pc1):",f1.Name())
      pc2, file2, line2, ok2 := runtime.Caller(2)
      logs.Error(" runtime.Caller(2) pc2:",pc2)
      logs.Error(" runtime.Caller(2) file2:",file2)
      logs.Error(" runtime.Caller(2) line2:",line2)
      logs.Error(" runtime.Caller(2) ok2:",ok2)
      f2 := runtime.FuncForPC(pc2)
      logs.Error(" runtime.FuncForPC(pc2):",f2.Name())
    
  • 输入结果

    2020/11/02 10:19:29.568 [E]   runtime.Caller(0) pc0: 18149024
    2020/11/02 10:19:29.571 [E]   runtime.Caller(0) file0: 
      E:/svn/golang/src/eastwan.com/xy-icnc/service/base/base_service.go
    2020/11/02 10:19:29.571 [E]   runtime.Caller(0) line0: 1087
    2020/11/02 10:19:29.571 [E]   runtime.Caller(0) ok0: true
    2020/11/02 10:19:29.572 [E]   runtime.FuncForPC(pc0): 
      eastwan.com/xy-icnc/service/base.Logs
    2020/11/02 10:19:29.573 [E]   runtime.Caller(1) pc1: 20331156
    2020/11/02 10:19:29.574 [E]   runtime.Caller(1) file1: 
      E:/svn/golang/src/eastwan.com/xy-icnc/service/device_tpm/device_tpm_service.go
    2020/11/02 10:19:29.574 [E]   runtime.Caller(1) line1: 362
    2020/11/02 10:19:29.575 [E]   runtime.Caller(1) ok1: true
    2020/11/02 10:19:29.575 [E]   runtime.FuncForPC(pc1): 
      eastwan.com/xy-icnc/service/device_tpm.TPFunStatisticTabAntData.func2.1
    2020/11/02 10:19:29.575 [E]   runtime.Caller(2) pc2: 4449304
    2020/11/02 10:19:29.576 [E]   runtime.Caller(2) 
      file2: D:/Program Files/go/Go/src/runtime/panic.go
    2020/11/02 10:19:29.576 [E]   runtime.Caller(2) line2: 975
    2020/11/02 10:19:29.576 [E]   runtime.Caller(2) ok2: true
    2020/11/02 10:19:29.577 [E]   runtime.FuncForPC(pc2): runtime.gopanic
    
  • 注意

    runtime.Caller 的通过不断迭代的方法获取信息,性能较差不建议使用

相关文章

网友评论

    本文标题:golang获取调用者的方法名及所在源码行数

    本文链接:https://www.haomeiwen.com/subject/pvugxltx.html