Hi,
I’m new to Go and the module and package system is fairly new to me.
I want to use Zerolog ( GitHub - rs/zerolog: Zero Allocation JSON Logger ) for logging. Most of the time I see people calling it directly, even the docs use a global instance. But isn’t this considered bad? Shouldn’t I create a logger instance and pass it around? ( Especially in terms of testing and mocking )
create a single logger instance, in your main.go, and pass that around. You get the extra advantage that if you ever want to change loggers or logging options, you only need to change one place.
I cannot really see any benefit of passing around an instance instead of using a global field. If you just define a global variable “logger” and use that everywhere, you can also just exchange it for another logger just like the passed reference. I would recon it makes many things easier.
Very personal opinion, I’ll try to avoid global variable as much as I can.
Usually I setup everything I need in the main() function and pass information to other components.