Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a Logger outside of main

Tags:

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?

like image 901
caiman Avatar asked Sep 03 '25 09:09

caiman


1 Answers

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()
}
like image 72
Denys Séguret Avatar answered Sep 05 '25 01:09

Denys Séguret