how to get correct file when I wrap a logger in go?

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

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...))
}

huangapple
  • 本文由 发表于 2015年12月10日 22:22:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/34204283.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定