执行生成以替换语句位置。

huangapple go评论110阅读模式
英文:

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

runtimeCaller()可以在这里帮助。

  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. )
  6. func Trace() (file string, funcName string, line int, ok bool) {
  7. pc, file, line, ok := runtime.Caller(1)
  8. f := runtime.FuncForPC(pc)
  9. return file, f.Name(), line, ok
  10. }
  11. func myFunc() {
  12. fmt.Println(Trace())
  13. }
  14. func main() {
  15. fmt.Println(Trace())
  16. myFunc()
  17. }

输出:

  1. /prog.go main.main 19 true
  2. /prog.go main.myFunc 15 true
英文:

Package runtime and Caller() can help here

  1. 1 package main
  2. 2
  3. 3 import (
  4. 4 "fmt"
  5. 5 "runtime"
  6. 6 )
  7. 7
  8. 8 func Trace () (file string, funcName string, line int, ok bool) {
  9. 9 pc, file, line, ok := runtime.Caller(1)
  10. 10 f := runtime.FuncForPC(pc)
  11. 11 return file, f.Name(), line, ok
  12. 12 }
  13. 13
  14. 14 func myFunc () {
  15. 15 fmt.Println(Trace())
  16. 16 }
  17. 17
  18. 18 func main() {
  19. 19 fmt.Println(Trace())
  20. 20 myFunc()
  21. 21 }

output:

  1. /prog.go main.main 19 true
  2. /prog.go main.myFunc 15 true

huangapple
  • 本文由 发表于 2014年12月24日 17:40:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/27634740.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定