DEV Community

Cover image for Logging approaches in Go
Chuck Ha
Chuck Ha

Posted on

Logging approaches in Go

During a kubeadm clean up cycle I found a neat feature of the glog library that made me think about various approaches to logging.

This flag is what set off my thought process:

  -log_backtrace_at value
        when logging hits line file:N, emit a stack trace
Enter fullscreen mode Exit fullscreen mode

I really needed this feature for the ticket I was working on, but it's not a feature I've seen in other logging libraries. glog takes the stance that logging should be global. You import the glog library and log whatever lines you need wherever you want. You don't configure glog with code, you configure it at runtime with flags. That's why glog requires you to run flag.Parse() before using it. glog gets the job done quickly as a global logger.

On the opposite end of the spectrum, you have logging as a proper dependency. The logger is a parameter to your function or exists on the struct. Either way, it's configurable via code which makes writing unit tests a lot easier. You don't have to resort to Go's testable examples to make sure your application is logging correctly. This approach is good when you rely on the output to be a certain way or depend on logs for more than just debug output. Check out logrus for a nice library that is easily wrapped to be a proper logging dependency.

As is the answer of almost every tech question, choose the method that works for the project at hand. Likely you'll end up somewhere in the middle and use both types of logging and that's ok. The only important thing is to treat each log type as it should be treated. So go ahead and skip unit testing of global loggers and don't forget to build in extra time for a well tested library by injecting the logging dependency.

Top comments (0)