In Go, when we need to implement the basic logging techniques, the “log” package is the go-to utility for such tasks.
One of the most powerful functions in the “log” package is the log.Fatal() function. This function allows us to log the messages and terminate the execution of a program with a non-zero exit code.
In this guide, we will teach you in great detail about the Fatal() function. We start with the basics and work our way to a more advanced functionality. We will also ensure to include examples and explanations to help you understand each functionality of this function.
What Is the Log Package?
Before diving into the workings of the Fatal() function, let us explore the parent package.
The “log” package is a built-in package and a part of the Go standard library that provides us with simple but powerful implementations to log the messages and errors in a Go application.
It plays a crucial role in debugging and adding a monitoring information during the development or even in the production of an app.
Some of the popular functions provided by the “log” package include:
- Printf
- Println
- Fatal
- Fatalf
Each of these functions writes the log messages to the standard error (os.Stderr) by default, but we can customize the output destination by configuring the package.
Golang Log.Fatal()
Now, let us move on to the Fatal() function.
What Is Log.Fatal?
As we mentioned, log.Fatal is one of the logging functions provided by the “log” package. When we call the Fatal() function, it prints the log message but it also immediately terminates the execution of the program with a non-zero exit code.
This is especially useful when dealing with errors that break the functionality of the program. Hence, instead of proceeding with potential errors, you simply terminate the execution and return an error message to the user.
The following shows the signature of the Fatal() function:
The v …interface{} parameter allows us to pass any number of arguments to be formatted and logged as a single message.
How It Works
The following is a high-level overview of what happens when we call the log.Fatal() function in a Go program:
- Formatting of the provided arguments into a single message string, similar to fmt.Printf() function
- Writing the message to the standard error stream (os.Stderror) along with the timestamp
- Program termination with a non-zero exit code, usually 1 to indicate that an error has occurred
- Cleanup operation which includes termination of any deferred functions
NOTE: If we customized the output destination of the function, the error message is forwarded to that destination rather than the standard error stream.
Example Usage:
Let us explore the various examples and features on how to use the Fatal() function in the Go programming language.
Example 1: Basic Usage
The following shows a very basic example on how to use the Fatal() function to log an error message and terminate the program:
import (
"errors"
"log"
)
func main() {
if err := errorFunc(); err != nil {
log.Fatal("An error occurred:", err)
}
}
func errorFunc() error {
return errors.New("func fail")
}
In the given example, we have a basic function called errorFunc() whose sole purpose is to return an error.
We then call the function in main and use log.Fatal() to log the error message and terminate the program.
The resulting output is as follows:
exit status 1
Example 2: Setting the Output Destination
By default, the function redirects the error message to the standard error stream of the target system. However, we can customize the output destination using the “SetOutput” function as shown in the following example:
import (
"errors"
"log"
"os"
)
func main() {
logFile, err := os.Create("error.log")
if err != nil {
log.Fatal("Error creating log file:", err)
}
defer logFile.Close()
log.SetOutput(logFile)
if err := errorFunc(); err != nil {
log.Fatal("An error occurred:", err)
}
}
func errorFunc() error {
return errors.New("fail")
}
In the given example, we start by creating a custom log file where we write the error messages.
We then configure the “log” package to write the error messages to the file using the log.SetOutput() function.
Now, if we run the given program, it should write any resulting errors to the file and terminate the program.
2023/11/28 08:08:06 An error occurred:fail
Example 3: Defer Cleanup
As we mentioned, any function that is deferred is executed before the program exits which makes it useful when cleaning up after the error.]
For example, it is good to close the log file before the program terminates. You can do this by adding the defer attribute.
Example 4: Adding a Context Information
When using the Fatal() function, it is good to add a context information which can help identify the source of the error message. For example, you can add an information such as the function name, variables, and more.
Conclusion
In this tutorial, we learned a lot about the “log” package in Go and how to use the log.Fatal() function to log the errors and terminate the program.