Golang Log Library: A Practical Guide

The log standard library in Golang can be used for logging purposes. Here are some common operations when using the log standard library.

  1. Import the log package.
import "log"
  1. Use the Println function to log information:
log.Println("This is a log message")
  1. Format log information using the Printf function.
log.Printf("This is a log message with a formatted string: %s", "Hello World")
  1. Set the prefix for logging output:
log.SetPrefix("LOG: ")
log.Println("This is a log message with prefix")
  1. Set the time format for logging output:
log.SetFlags(log.Ldate | log.Ltime)
log.Println("This is a log message with timestamp")
  1. Output logs to a file:
file, err := os.OpenFile("logfile.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
    log.Fatal(err)
}
defer file.Close()

log.SetOutput(file)
log.Println("This is a log message that will be written to the file")

Here are some basic operations using the log standard library. You can use more log library functions based on your actual needs. Please note that the log standard library by default outputs to standard error stream, you can use the log.SetOutput function to redirect the log output to other places.

bannerAds