目前golang学习网上已经有很多关于Golang的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《如何在 Go 中初始化 zap 记录器并在不同文件中共享?》,也希望能帮助到大家,如果阅读完后真的对你学习Golang有帮助,欢迎动动手指,评论留言并分享~
我正在尝试从漂亮的 logrus(对调试非常有帮助)迁移我的应用程序,并引入 uber 日志框架 zap。
使用 logrus,我只能初始化记录器一次并从其他 go 文件中重用它,例如:
package main
import(
// print filename on log
filename "github.com/onrik/logrus/filename"
// very nice log library
log "github.com/sirupsen/logrus"
)
func main(){
// ==== set logging
formatter := new(log.textformatter)
formatter.timestampformat = "jan _2 15:04:05.000000000"
formatter.fulltimestamp = true
formatter.forcecolors = true
log.addhook(filename.newhook()) // print filename + line at every log
log.setformatter(formatter)
}
从其他 go 文件中,我可以重用该记录器而无需任何其他初始化:
// VerifyCommandLineInput is delegated to manage the inputer parameter provide with the input flag from command line
func VerifyCommandLineInput() datastructures.Configuration {
log.Debug("VerifyCommandLineInput | Init a new configuration from the conf file")
c := flag.String("config", "./conf/test.json", "Specify the configuration file.")
flag.Parse()
if strings.Compare(*c, "") == 0 {
log.Fatal("VerifyCommandLineInput | Call the tool using --config conf/config.json")
}
file, err := os.Open(*c)
if err != nil {
log.Fatal("VerifyCommandLineInput | can't open config file: ", err)
}
defer file.Close()
decoder := json.NewDecoder(file)
cfg := datastructures.Configuration{}
err = decoder.Decode(&cfg)
if err != nil {
log.Fatal("VerifyCommandLineInput | can't decode config JSON: ", err)
}
log.Debug("VerifyCommandLineInput | Conf loaded -> ", cfg)
return cfg
}
我的问题是:使用 zap 日志框架,如何在 main 函数中初始化日志并使用其他 go 文件中的记录器?
解决方案
您可以在主函数中设置记录器并调用 zap.ReplaceGlobals 将其用作默认的全局记录器。
ReplaceGlobals 替换全局 Logger 和 SugaredLogger,并返回一个函数来恢复原始值。并发使用是安全的。
用 zaps 的实现替换默认的 go Global 记录器是可能的,但不鼓励。
根据他们的FAQ
根据您的需要,您可以在 main 中创建一个记录器并将其传递,或者在每个包中创建一个新的记录器。我选择在 main 中创建一个并将其传递,因为我使用的是 Atomic 记录器,它允许我在应用程序通过 API 调用运行时更改日志级别。有着使用 DI 和整合代码的悠久历史,它确实感觉像代码味道,但显然它对于 zap 如何通过单例或全局传递它的性能明显更高。
今天关于《如何在 Go 中初始化 zap 记录器并在不同文件中共享?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
本文内容来源于互联网,如有侵权请联系删除。
