Logging Simultaneously to Console and File in Go
To direct log messages to a file, the code typically uses log.SetOutput(logFile). However, if you desire both console output and logging to a file, here's a solution using io.MultiWriter.
What is io.MultiWriter?
An io.MultiWriter allows writing data to multiple destinations simultaneously. It resembles the behavior of the Unix tee command.
Solution
To log to both the console and a file:
logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666) if err != nil { panic(err) }
mw := io.MultiWriter(os.Stdout, logFile)
log.SetOutput(mw)
Example
package main import ( "log" "os" "io" ) func main() { logFile, err := os.OpenFile("log.txt", os.O_CREATE | os.O_APPEND | os.O_RDWR, 0666) if err != nil { panic(err) } mw := io.MultiWriter(os.Stdout, logFile) log.SetOutput(mw) log.Println("This is a log message") }
The above is the detailed content of How to Log to Both Console and File Simultaneously in Go?. For more information, please follow other related articles on the PHP Chinese website!