在上一篇go实用小技能-自定义log输入格式分享了go自带的log包自定义输出格式。当我们把flag设置为 log.Llongfile 或 log.Lshortfile的时候,系统自动会将当前正执行的文件名和行数打印出来。这其中的机制有些小伙伴一定很困惑,其实log包是调用runtime.Caller实现的。我们来看看log包下面的Output方法
func (l *Logger) Output(calldepth int, s string) error {
now := time.Now() // get this early.
var file string
var line int
l.mu.Lock()
defer l.mu.Unlock()
// 这里是判断用户将flat设置为Lshortfile 或 Llongfile
// 这里用到 位或 和 位与 运算符,不明白的小伙伴可以百度一下
if l.flag&(Lshortfile|Llongfile) != 0 {
// release lock while getting caller info - it's expensive.
l.mu.Unlock()
var ok bool
// 重点在这里,
// 通过方法名,我们知道Caller是public, so ^>^ 我们就可以自己调用了
_, file, line, ok = runtime.Caller(calldepth)
if !ok {
file = "???"
line = 0
}
l.mu.Lock()
}
l.buf = l.buf[:0]
l.formatHeader(&l.buf, now, file, line)
l.buf = append(l.buf, s...)
if len(s) == 0 || s[len(s)-1] != 'n' {
l.buf = append(l.buf, 'n')
}
_, err := l.out.Write(l.buf)
return err
}
接下来我们自己调用runtime.Caller看一下效果
package main
import (
"log"
"runtime"
)
func main() {
Caller0()
}
func Caller0() {
Caller1()
}
func Caller1() {
Caller2()
}
func Caller2() {
var skip int
for {
skip++
pc, file, line, ok := runtime.Caller(skip)
if ok {
log.Printf("pc:%v, file:%s, line:%d, ok:%v skip:%d n", pc, file, line, ok, skip)
} else {
break
}
}
}
// 下面是这个程序的输入内容:
// 通过输出的内容可以看到 随着 skip的变化,打印出来的行数也要着变化 Caller2 > Caller1 > Caller0
//
// 2016/12/22 15:47:32 pc:8340, file:/Users/ayou/go/src/github.com/wuciyou/godoc/runtime/runtime.go, line:16, ok:true skip:1
// 2016/12/22 15:47:32 pc:8308, file:/Users/ayou/go/src/github.com/wuciyou/godoc/runtime/runtime.go, line:12, ok:true skip:2
// 2016/12/22 15:47:32 pc:8276, file:/Users/ayou/go/src/github.com/wuciyou/godoc/runtime/runtime.go, line:9, ok:true skip:3
// 2016/12/22 15:47:32 pc:166212, file:/usr/local/go/src/runtime/proc.go, line:183, ok:true skip:4
// 2016/12/22 15:47:32 pc:333425, file:/usr/local/go/src/runtime/asm_amd64.s, line:2086, ok:true skip:5
欢迎加入 dogo 技术交流群:437274005 点击右侧按钮快捷加入