Using package-level global variables
The apex
and logrus
packages in the earlier examples both used a package-level global variable. Sometimes, it's useful to structure your libraries to support both structs with a variety of methods and top-level functions so that you can use them directly without passing them around.
This recipe also demonstrates using sync.Once
to ensure that the global logger will only be initialized once. It can also be bypassed by the Set
method. The recipe only exports WithField
and Debug
, but one can imagine exporting every method attached to a log
object.
Getting ready
Configure your environment according to these steps:
- Refer to the Getting ready section of the Handling errors and the Error interface recipe.
- Run the
go get github.com/sirupsen/logrus
command.
How to do it...
These steps cover writing and running your application:
- From your terminal/console application, create the
chapter4/global
directory and navigate to it. - Copy tests from https://github.com/agtorre/go-cookbook...