golang 获取当前文件名和行号的方法 - Go语言中文社区

golang 获取当前文件名和行号的方法


golang 的runtime库,提供Caller函数,可以返回运行时正在执行的文件名和行号:

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

Caller reports file and line number information about function invocations on the calling goroutine's stack. The argument skip is the number of stack frames to ascend, with 0 identifying the caller of Caller. (For historical reasons the meaning of skip differs between Caller and Callers.) The return values report the program counter, file name, and line number within the file of the corresponding call. The boolean ok is false if it was not possible to recover the information.

调用方法如下,返回的file为绝对路径,line为行号。有了这个就可以在自己的日志等函数中添加这个记录了。

_, file, line, ok := runtime.Caller(1)

转载于:https://my.oschina.net/u/1765027/blog/799964

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_34051201/article/details/92146660
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-14 10:40:11
  • 阅读 ( 1733 )
  • 分类:Go

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢