golang提供运行时堆栈调用接口runtime.Caller。所有的日志库都是基于该接口实现日志中打印日志输出所在文件、行号。
1 | package main |
输出结果:
1 | [info]2020-04-20 11:42:06 main.go:12 doSomething: [hello world] |
这里输出的日志行号显示为12。行号12所在的位置不是实际想要显示的日志位置。实际想要显示的日志位置在24行。这里只需要设置runtime.Caller(1)就可以了。
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.Caller 函数报告有关调用goroutine堆栈上的函数调用的文件和行号信息。
参数skip是要提升的堆栈帧数,其中0标识Caller的调用方。(由于历史原因,在Caller和Callers之间,跳过的含义有所不同。)
返回值报告相应调用文件中的程序计数器,文件名和行号。
如果不可能恢复该信息,则ok布尔值为False。
以go.uber.org/zap日志库为例,它也提供了设置该skip的设置,以方便对其进行二次包装。
1 | lgcfg = zap.Config{ |