如何在主函数之外使用日志记录器

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

How to use a Logger outside of main

问题

我正在使用logger包github.com/jcelliott/lumber来进行Go语言的日志记录,并且我像这样声明和使用它:

func main() {
    log := lumber.NewConsoleLogger(lumber.DEBUG)
    ...
    log.Error("File error: %v\n", e)
}

如何从main函数之外的函数中进行日志记录呢?显然,这里的log变量是在main函数内部声明的,这限制了它的作用域,但我还没有找到在Go语言中使用全局变量的方法,有没有比在每个函数中重新声明日志记录器更好的方法呢?

英文:

I am using logger package github.com/jcelliott/lumber for logging in go, and I declare and use it like this:

func main() {
log := lumber.NewConsoleLogger(lumber.DEBUG)
...
log.Error("File error: %v\n", e)
}

How can I log from functions outside of main? Obviously here log is declared within main and that limits its scope, but I haven't found a way to have global variables in GO, is there a better way than re-declaring the logger in each function?

答案1

得分: 4

声明全局变量的方式如下:

var log lumber.Logger

func anyFunc() {
    log.Error("File error: %v\n", e)
}

func main() {
    log = lumber.NewConsoleLogger(lumber.DEBUG)
    anyFunc()
}

请注意,这是一个Go语言的示例代码,其中使用了一个名为lumber的日志库。在这段代码中,首先声明了一个全局变量log,类型为lumber.Logger。然后,在anyFunc函数中,使用log.Error方法记录错误信息。在main函数中,通过lumber.NewConsoleLogger创建了一个控制台日志记录器,并将其赋值给log变量。最后,调用anyFunc函数来记录日志。

英文:

Declare your global variable like this :

var log lumber.Logger

func anyFunc() {
  log.Error("File error: %v\n", e)
}

func main() {
  log = lumber.NewConsoleLogger(lumber.DEBUG)
  anyFunc()
}

huangapple
  • 本文由 发表于 2013年10月5日 22:48:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/19199021.html
匿名

发表评论

匿名网友

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

确定