How to handle and log errors with the log package in Go?

To handle and log errors with the log package in Go, you can follow these steps:

  1. Import the log package:
import "log"
  1. Set the output to a file or standard output:
log.SetOutput(os.Stdout) // set output to standard output // OR file, err := os.OpenFile("logfile.log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) if err != nil { log.Fatal(err) } defer file.Close() log.SetOutput(file) // set output to a file
  1. Set the log prefix and flags:
log.SetPrefix("ERROR: ") log.SetFlags(log.LstdFlags | log.Lmicroseconds) // Use desired flags
  1. Handle and log errors:
err := SomeFunction() if err != nil { log.Printf("Error occurred: %v", err) // or log.Fatal("Fatal error occurred: ", err) // or log.Panic("Panic occurred: ", err) }

You can choose one of the following log functions based on your requirements:

  • log.Print(v ...interface{}) or log.Println(v ...interface{})
    • Prints the log message with the provided values.
  • log.Printf(format string, v ...interface{})
    • Formats and prints the log message.
  • log.Fatal(v ...interface{}) or log.Fatalln(v ...interface{})
    • Prints the log message with the provided values and exits the program with a non-zero status code.
  • log.Fatalf(format string, v ...interface{})
    • Formats and prints the log message, then exits the program with a non-zero status code.
  • log.Panic(v ...interface{}) or log.Panicln(v ...interface{})
    • Prints the log message with the provided values and causes a panic.
  • log.Panicf(format string, v ...interface{})
    • Formats and prints the log message, then causes a panic.

With these steps, you can handle and log errors using the log package in Go.