英文:
go generate to substitute statement location
问题
我正在使用一个策略来在代码中添加日志语句的位置。
例如:fmt.Println("main.go:myFunction(): There was an error:", e)
我该如何使用go generate来实现以下功能:
fmt.Println("%fn%: There was an error:", e)
并且它会替换为Go文件的名称、封闭函数的名称和行号?
英文:
I'm using a policy to add the location of the log statement in code.
Eg. fmt.Println("main.go:myFunction(): There was an error:", e)
How would I use go generate to do something like
fmt.Println("%fn%: There was an error:", e)
and it will substitute the name of the go file, the enclosing function name, and the line number?
答案1
得分: 4
package main
import (
"fmt"
"runtime"
)
func Trace() (file string, funcName string, line int, ok bool) {
pc, file, line, ok := runtime.Caller(1)
f := runtime.FuncForPC(pc)
return file, f.Name(), line, ok
}
func myFunc() {
fmt.Println(Trace())
}
func main() {
fmt.Println(Trace())
myFunc()
}
输出:
/prog.go main.main 19 true
/prog.go main.myFunc 15 true
英文:
Package runtime and Caller() can help here
1 package main
2
3 import (
4 "fmt"
5 "runtime"
6 )
7
8 func Trace () (file string, funcName string, line int, ok bool) {
9 pc, file, line, ok := runtime.Caller(1)
10 f := runtime.FuncForPC(pc)
11 return file, f.Name(), line, ok
12 }
13
14 func myFunc () {
15 fmt.Println(Trace())
16 }
17
18 func main() {
19 fmt.Println(Trace())
20 myFunc()
21 }
output:
/prog.go main.main 19 true
/prog.go main.myFunc 15 true
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论