Basics of Logging in Go

507 VIEWS

· ·

Logging is an essential part of supporting the complete application life cycle. Logs support us all the way from creation to debugging to planning new features. By analyzing the data in the logs, we can glean insights, resolve bugs much quicker, and detect problems early and as they happen.

This post will discuss the who, what, when, where, how, and why of logging. Later in this post, the “how” section will give insights into using code. But to kick it off, we’ll briefly cover who uses logs.

Logging is the process of recording state and program-related data such as inputs and outputs, processes into files, or a console for later access.

Logging is one of the software development workflow’s most critical parts. Logs can provide context to the state of an application, and they are useful for record-keeping, monitoring, debugging, troubleshooting, and program management.

Getting Started With Logging in Go

Since logging is important in software development, most programming languages, including Go, have functionalities for logging in their standard libraries.

Go provides logging and logging-related functionalities in the log package. The log package defines a Logger type with methods for formatting input, output, errors, and interacting with the program’s control flow.

You don’t need to install any packages or make any configurations to use the log package. Simply add the log identifier to your import statements as thus.

import "log"

It is crucial to use the log package because, along with logging specific functionalities, the log package is more secure than the fmt package; the log package is also safe from concurrent goroutines, unlike the fmt package.

Popular Logging Functions

There are many useful functions in the log package for logging on different levels to specified outputs.

The Println and Printf output the logged message to the console. The Printf method is a C-style formatting method, and you can use Go string formatting verbs with the Printf method, unlike the Println method, which returns the log text on a new line to the standard output.

log.Println("INFO: Example Log Message")
log.Printf("%s INFO: Example Log Message", "Error Type")

You can use the Fatalln, Fatal and Fatalf methods for fatal issues and errors.

The Fatalln method outputs the specified message on a new line to the standard output and exits the program with the os.Exit(1) method. The Fatal and Fatalf methods operate the same as the Fatalln method, except that they don’t output on new lines, and the Fatalf method is a C-style formatting method.

log.Fatalln("Fatal: Fatal Error Signal")
log.Fatal("Fatal: Fatal Error Signal")
log.Fatalf("%s Fatal: Fatal Error Signal", "Error Type")

You can also use the built-in panic function with a logger from the log package. The Panic, Panicln, and Panicf methods of the log package log to the console and execute the panic function. These methods are useful when you’re working with Goroutines.

log.Panic("Error: Panic Error Message")
log.Panicln("Error: Panic Error Message")
log.Panicf("%s Error: Panic Error Message", "program panicked")

There’s a Writer method in the log package that implements the io.Writer interface. You can use this method to write to any standard output.

log.Writer()

Unfortunately, the log package doesn’t provide any functionalities for structured logging. For structured logging, you can work with third-party logging packages like Zap and Logrus.

Logging to Files With Go

Log files are one of the popular tools for working with Logs, and you can log to files in Go with the log package.

You’ll have to open a file with the os package before appending logs. You can open a file with the OpenFile method of the os package. The OpenFile method takes in the file name, options, and mode.

file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
   log.Fatalf("%s Fatal: Fatal Error Signal")
}

The options are set to create or append on read and write only, and the file mode is set to read and write permissions.

You can use a defer statement to close the file after your operation.

The SetOutput method of the log package takes in the file instance and sets the logs for output in the file.

defer file.Close()
log.SetOutput(file)

After using the SetOutput method, the log package directs subsequent logs to the file.

log.Printf("%s INFO: Example Log Message", "Error Type")

Logging in Go

Conclusion

You’ve learned about logging, using the functions in the log package, and logging files in Go, all with the built-in log package.

You want to ensure you’re logging important information at different levels, especially since logs come in handy during troubling times.


Ukeje Goodness Chukwuemeriwo is a Software developer and DevOps Enthusiast writing Go code day-in day-out.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published.

Menu
Skip to toolbar