How to log messages with different log levels (e.g., info, warning, error) in Go?

In Go, you can log messages with different log levels using the standard library's log package. Here's how you can do it:

  1. Import the log package:
import "log"
  1. Set the desired log level:
log.SetFlags(log.LstdFlags | log.Lmicroseconds) // Optional: Set log flags log.SetPrefix("[INFO] ") // Optional: Set log prefix // Set the desired log level log.SetOutput(os.Stdout) // Log everything (default) log.SetOutput(ioutil.Discard) // Disable logging completely
  1. Log messages with the desired log level:
log.Println("This is a general log message") log.Printf("This is a log message with formatting - %s", "Hello") log.Print("This is another log message") // Log a warning message log.Println("[WARNING] This is a warning message") // Log an error message log.Fatalln("[ERROR] This is an error message")

The above code demonstrates logging messages with different log levels in Go. By default, all log messages are printed to the standard output. However, you can customize the log level, format, and output destination as per your requirements.

Note: Fatalln logs the error message and then calls os.Exit(1), which means the program execution will stop immediately after logging the message.