How to set up and configure a basic logger in Go?

To set up and configure a basic logger in Go, you can use the log package in the standard library. Here's a step-by-step guide:

  1. Import the log package in your Go file:
import "log"
  1. Create an instance of the log.Logger struct and specify the output destination:
logger := log.New(os.Stdout, "LOG: ", log.Ldate|log.Ltime)

This example sets the logger to write log messages to the standard output (os.Stdout) and adds a prefix ("LOG: ") to each log message.

  1. You can also customize the log prefix, flags, and output destination by modifying the respective properties of the log.Logger instance.
logger.SetPrefix("MYAPP: ") logger.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) logger.SetOutput(file)
  1. You can now use the logger to write log messages at different severity levels:
logger.Println("This is a log message.") // Output example: LOG: 2022/01/01 12:00:00 This is a log message. logger.Printf("This is a %s message.\n", "formatted") // Output example: LOG: 2022/01/01 12:00:00 This is a formatted message. logger.Fatal("This is a fatal error.") // Terminates the program after logging the message logger.Panic("This is a panic message.") // Triggers a panic after logging the message

Note: By default, the log package outputs log messages with the time and date. You can customize the flags passed to SetFlags to modify the log format.

That's it! You have set up a basic logger in Go using the log package. Remember to import the necessary packages and adjust the configuration to suit your needs.