golang runtime.Caller(skip int) 介紹

函數原型,及官方描述:

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.

該方法在日誌打印時會用到, 用來獲取當前調用棧幀所在的文件行號,及文件名信息,這樣方便開發人員在同一位置獲取需要的調用處的文件信息;

從官方描述可以知,參數 skip 是用來控制當前調用棧哪個幀的信息, skip 爲 0 時,表示輸出當前棧幀的文件名及行號信息,

skip 爲 1 時,輸出當前調用棧上一幀的文件名及行號, 下面是輸出結果,可以看到,在同一函數內調用,獲取到的 file 是可以不同的:

main.go

 package main
 
  import "test/log-trace/log"
  
  func main() {
      log.PrintFileAndLine()
  }

log/log.go

package log

import (
	"fmt"
	"path"
	"runtime"
)

func WritFileAndLine(skip int) {
	_, file, line, ok := runtime.Caller(skip)
	if !ok {
		file = "???"
		line = 0
	} else {
		file = path.Base(file)
	}

	fmt.Println("the file: ", file, ", and line: ", line, " with skip=", skip)
}

func PrintFileAndLine() {
	WritFileAndLine(0)
	WritFileAndLine(1)
	WritFileAndLine(2)
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章