英文:
how to get correct file when I wrap a logger in go?
问题
我像这样使用一个全局日志记录器:
[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")
}
在main
函数中,我想要得到以下输出:
[Debug] 2015/12/10 22:20:23 /tmp/log/src/main/main.go:6: in main
但是我得到了以下输出:
[Debug] 2015/12/10 22:20:23 /tmp/log/src/logging/logging.go:16: in main
我该如何获取调用日志记录器的正确文件?
英文:
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?
答案1
得分: 3
不要使用logger.Printf
,而是使用原始的logger.Output
函数,并为调用点提供正确的callDepth
(默认为2)。
如果你查看Logger.Printf
的代码,你可以看到默认的实现方式:
func (l *Logger) Printf(format string, v ...interface{}) {
l.Output(2, fmt.Sprintf(format, v...))
}
英文:
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...))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论