去生成替代语句位置

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?

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