Home >Backend Development >Golang >How to Log to Both Console and File in Go?
Logging to Both Console and File in Go
In Go, you can easily direct log messages to a file using log.SetOutput(logFile). But what if you also want to display these messages in the console?
Using io.MultiWriter
To achieve this, you can use io.MultiWriter. This creates a writer that duplicates its writes to all the provided writers. This is similar to the Unix tee(1) command.
logFile, err := os.OpenFile("log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) if err != nil { panic(err) } // Create a MultiWriter that writes to both the console and the file. mw := io.MultiWriter(os.Stdout, logFile) // Set the logger's output to the MultiWriter. log.SetOutput(mw)
In this example, the only change from the original code is the creation of the io.MultiWriter and setting the logger's output to it. Now, all log messages will be written to both the console and the specified file, providing a convenient way to monitor logs in real-time while also maintaining a persistent log.
The above is the detailed content of How to Log to Both Console and File in Go?. For more information, please follow other related articles on the PHP Chinese website!