You can find a working example on my GitHub: https://github.com/seblegall/blog-scripts/tree/master/logrus-cobra
I recently had to refactor the way one of my app print logs. My idea was to user
logrus as it is a very well known lib to produce logs with Go.
Logrus is let you print nicely color-coded and structured logs and is completely API compatible with the standard library logger.
My first question was about log level and how to setup the log level once across all sub-directory/package of my project.
Under the hood, logrus instantiate a new variable
log in the package. One done, calling the
logrus.SetLevel() function will store the level directly in this newly instantiated struct.
Thus, we have a global struct, available across all sub-package making the level automatically shared without having to use dependency injection.
If you need to set a different level in one sub-package (for example), you just need to instantiate a new logger :
var log = logrus.New() //... log.Debug("debug log")