How to use the built-in log package for debugging and logging in Go?

To use the built-in log package for debugging and logging in Go, you can follow these steps:

  1. Import the log package by adding the following line at the beginning of your Go file:

    import "log"
  2. Start using the logging functions provided by the package. The most commonly used ones are Print, Printf, Println, Fatal, Fatalf, and Fatalln. These functions write the log message to the standard logger:

    log.Print("This is a log message") // Write log message without any formatting. log.Printf("Count: %d", count) // Write log message with formatting. log.Println("This is another log message") // Write log message and add a newline at the end. log.Fatal("Fatal error occurred") // Write log message and terminate the program with exit code 1. log.Fatalf("Fatal error occurred: %s", err) // Write log message with formatting and terminate the program with exit code 1. log.Fatalln("Fatal error occurred, exiting...") // Write log message and a newline at the end, then terminate the program with exit code 1.
  3. By default, log messages are written to the standard error. If you want to redirect the logs to a specific file or an io.Writer, you can set the output of the logger using the SetOutput function:

    file, err := os.OpenFile("application.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { log.Fatal("Failed to open log file:", err) } defer file.Close() log.SetOutput(file)
  4. You can also control the log prefix that is printed before each log message by using the SetPrefix function:

    log.SetPrefix("[MY_APP]")
  5. If you want to include the date and time in each log message, you can use SetFlags function with the log.Ldate and log.Ltime flags:

    log.SetFlags(log.Ldate | log.Ltime)

    This will prepend each log message with the current date and time.

Note that the built-in log package is simple and suitable for basic logging needs. If you require more advanced logging features, consider using a more powerful third-party logging package like logrus or zap.