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

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

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()可以在这里帮助。

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

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:

确定