How to Log Messages to Multiple Destinations in Go
When logging messages in Go, it may be necessary to output logs to both the console and a file simultaneously. While it's straightforward to direct messages solely to a file using log.SetOutput(logFile), there's a way to enable logging in both terminals and target files.
Implementing Multiple Destinations
To achieve logging in multiple destinations, utilize the io.MultiWriter. As implied by its name, MultiWriter facilitates writing to multiple writers concurrently, similar to the Unix tee(1) command.
Here's how to implement this using MultiWriter:
import ( "os" "io" "log" ) func main() { logFile, err := os.OpenFile("log.txt", os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666) if err != nil { panic(err) } // Initialize io.MultiWriter to write to both file and console mw := io.MultiWriter(os.Stdout, logFile) // Set output to MultiWriter log.SetOutput(mw) }
In this example, mw is an io.MultiWriter instance that writes to both os.Stdout (console) and the logFile. By setting log.SetOutput(mw), all subsequent log messages will be printed in the console and logged to the specified file.
以上是如何在 Go 中將訊息記錄到控制台和檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!