How to Log in Golang

Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Want to learn how to build better Go applications faster and easier? You can.

Check out my course on the Go Standard Library. You can check it out now for free.


In Go, you can use the log package to do logging. Here is an example of how you can use the log package to log messages at different levels:

package main

import (
	"log"
)

func main() {
	log.Println("This is a log message.")
	log.Fatalln("This is a fatal error.")
	log.Panicln("This is a panic.")
}

In the example above, log.Println is used to log a message at the “info” level, log.Fatalln is used to log a message at the “fatal” level, and log.Panicln is used to log a message at the “panic” level.

By default, the log package writes log messages to the standard error (stderr) output, with the timestamp and the log level included in the output. You can customize the output of the log messages by setting the flags for the logger. For example, you can use the log.SetFlags function to set the logger flags to include the file and line number of the logging call:

log.SetFlags(log.LstdFlags | log.Lshortfile)

You can also use the log.SetOutput function to set the output destination for the log messages. For example, you can use it to write the log messages to a file:

f, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
	log.Fatal(err)
}
defer f.Close()

log.SetOutput(f)

By default, the log package logs messages at the “info” level and above (i.e., “warning”, “error”, “fatal”, and “panic”). You can use the log.SetLevel function to set the minimum log level that will be logged. For example, you can use it to only log messages at the “warning” level and above:

log.SetLevel(log.WarnLevel)

You can also use third-party logging libraries, such as zap, logrus, or go-kit/log, which provide more advanced features and customization options.



Stay up to date on the latest in Coding for AI and Data Science

Intuit Mailchimp