2021年10月21日 星期四

紀錄一下如何取得當前執行的函數

參考自 golang log package的原始碼
var calldepth = 2
pc, file, line, ok := runtime.Caller(calldepth)
package foo

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


func Log(message string) {
	filePath, f, line := getCaller()
	_, file := path.Split(filePath)
	fmt.Printf("[%s.%s:%d] %s\n", file, f, line, message)
}

func getCaller() (file string, functionName string, line int) {
	var calldepth = 2
	pc, file, line, ok := runtime.Caller(calldepth)
	if !ok {
		return
	}
	functionName = runtime.FuncForPC(pc).Name()
	return
}

參考資料

smallnest. (2018, November 3). 如何在Go的函数中得到调用者函数名? 鸟窝. https://colobu.com/2018/11/03/get-function-name-in-go/

沒有留言:

張貼留言