Adding Logs in the App

Learn about logging in Go apps and how to be consistent with them.

Logging is the process of printing or outputting information about an application from its source code. Logs are an indispensable part of an application because they:

  • Keep a history of application behavior, including information related to business, the functions that were executed, and the data the functions received and processed.

  • Store any errors that might have occurred and their traces. This is especially useful in cases when the app malfunctions.

  • Help understand the workflow in an app.

  • Can be used for analytics to understand the traffic and usage patterns of the app.

While these benefits sound awesome, logs are only as good as their keepers. That's why it's very important to decide how we plan on using these logs before actually writing them.

What to log

So, what are some of the most obvious things we should include in a log? A log should ideally have the following:

  • Timestamp: To track when that particular workflow was hit.

  • Name of the service or application: To help keep track of the service these logs belong to.

  • Function or module name: To give further context about the current execution point.

  • Actual message string: To provide more context to the information being logged.

Now that we know what we will be logging, let's actually try to add some logs to our Go app.

Logging in Go

Go, with its built-in log package, makes it super easy to get started with logging. The package has all the basic functions we need to get started. Let's look at an example to understand how logging works in Go.

Here's a very simple program:

Get hands-on with 1400+ tech skills courses.