Log Levels and Structured Logging

Understand the different log levels available in Go and the value structured logging adds to an app.

Logging in an app can be as simple or as complicated as we want it to be. It all depends on how the logs are going to be used. While Go's built-in library is good for basic logging, it lacks a lot of advanced features that other third-party packages can provide out of the box.

Some of them, like Zap from Uber, are blazing fast, while Logrus and Zerolog are great for structured logging. Wait, what's structured logging? We'll discuss it soon enough in this lesson.

But before we get into using any of these libraries, let's tackle the first step toward organizing and structuring logs: log levels.

Log levels

Adding logs to our code is considered good practice. It not only helps another developer understand the code better but also helps in debugging an issue when one occurs.

But too many logs could lead to huge log files, making it difficult for a human to parse through them to figure things out. Log levels help us maintain the balance between logging the necessary information without overdoing it by organizing logs into multiple levels. We can then choose which levels should be stored and which are not required at the moment, and we can switch between them as per our requirements. The most commonly used levels are:

  • Info: This level is for logs that are only providing extra information about the workflow being executed. This may include information like which service is hit and whether the web server has started or not.

  • Error: This level is for logging any errors that might have occurred. This can include information about when one or more of our functions returned an error.

  • Debug: This level is for logs that can be useful during debugging. This can include the inputs a function is receiving.

There are still other levels, like Trace, Warn, Fatal, and Panic.

Most libraries in Go support these log levels among others. But unfortunately, log doesn't. So let's look at an example in which we will log the messages at different levels using the go-kit package. The go-kit package is a collection of essential but simple libraries.

Get hands-on with 1200+ tech skills courses.