Should you use a global logger instead of passing around an instance?

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 )

To me it feels weird to call

zerolog.TimeFieldFormat = zerolog.TimeFormatUnix

somewhere in the code and it modifies the logger.

Is Go different? Should I simply import the logging package and use it? Or is this example GitHub - rs/zerolog: Zero Allocation JSON Logger the “clean” one?

Thanks in advance

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.

Yes, thought so :slight_smile: Think the examples are misleading a little bit ( or just simplified )

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.

1 Like

Hi @falco467

What about when you need different configs in different packages ?

I would create a package wide single logger mypackage.log derived from the global instance and use it everywhere in the package.

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.

This will make also easier testing

and check out the new structured logging package slog package - golang.org/x/exp/slog - Go Packages package, which will move to the standard library in 1.21 (next month).

ahh yes, forgot to mention slog, I’m using it since months in all my projects.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.