golang 获取当前文件名和行号的方法
Mr_李辉 · · 16076 次点击 · · 开始浏览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)
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
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)