Home >Backend Development >Golang >How to Log to Both Console and File in Go?

How to Log to Both Console and File in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 17:51:031004browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn