How to format log messages with timestamps in Go?

In Go, you can format log messages with timestamps by using the log package combined with the time package. Here's an example:

package main import ( "log" "os" "time" ) func main() { log.SetOutput(os.Stdout) // Set log output to stdout log.SetFlags(log.Ldate | log.Ltime) // Set log flags to include date and time log.Println("This is a log message") // You can also customize the log format by defining a custom log formatter log.SetPrefix("[CustomPrefix] ") log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds) log.Println("This is a custom formatted log message") }

In this example, the log.SetFlags function is used to specify the desired log format with the help of log flags. The flags log.Ldate and log.Ltime are used to include the current date and time in the log message. You can include more flags based on your requirements, such as log.Lmicroseconds to include microseconds.

By default, the log messages are written to the standard error stream (os.Stderr). In the example above, we set the log output to os.Stdout to redirect the log messages to the standard output stream.

The log.Println function is used to write log messages with timestamps. You can also use log.Printf to log formatted messages.

Remember to import the necessary packages: log, os, and time.

This is just a simple example, and you can explore more advanced logging libraries like logrus or zap for more log formatting options and features.