I use a global logger like this:
[root@dev log]# cat src/logging/logging.go
package logging
import (
"log"
"os"
)
var Logger *log.Logger
func init() {
Logger = log.New(os.Stdout, "[Debug]", log.Llongfile|log.LstdFlags)
}
func Debug(format string, v ...interface{}) {
Logger.SetPrefix("[Debug] ")
Logger.Printf(format, v...)
}
[root@dev log]# cat src/main/main.go
package main
import "logging"
func main() {
logging.Debug("in main")
}
Here in main function I want to get:
[Debug] 2015/12/10 22:20:23 /tmp/log/src/main/main.go:6: in main
But I get following output instead:
[Debug] 2015/12/10 22:20:23 /tmp/log/src/logging/logging.go:16: in main
How can I get the correct file which calling the logger?
Instead of using logger.Printf
, you need to use the raw logger.Output
function, and provide the correct callDepth
for the call point (the default is 2).
If you look at the code for Logger.Printf
, you can see how it's done by default:
func (l *Logger) Printf(format string, v ...interface{}) {
l.Output(2, fmt.Sprintf(format, v...))
}