The log.Logger methods call Logger.Output() to send a message to the appropriate output. Logger.Output() allows you to pass calldepth (number of frames skipped).
Unfortunately, the log.Logger methods contain a wired-in calldepth , so you cannot provide an offset to skip the frame of the wrapper function.
But a much better alternative is to call this Logger.Output() from your wrapper, so you don't have to worry about frames and lines yourself. Also note that you do not need to add a new line "\n" , since the type log.Logger already does this if the message to be logged does not end with a new line.
So, a better and shorter alternative:
var myLogger = log.New(os.Stdout, "[my]", log.Lshortfile) func info(pattern string, args ...interface{}) { myLogger.Output(2, fmt.Sprintf(pattern, args...)) }
Testing:
func main() { log.SetFlags(log.Lshortfile) log.Println("hello") info("world") }
Exit (try on the Go Playground ):
main.go:11: hello [my]main.go:12: world
As you can see, info() prints the correct line number (+1 compared to the line number printed by log.Println() in the previous line).
icza
source share