Redirecting Command Output to Console and Log File Simultaneously
To redirect the stdout and stderr of a command to both the console and a log file in real time, you can employ the io.MultiWriter type in Go. Here's how:
In the code snippet provided, the code redirects only to the console because the Stdout and Stderr fields of the cmd are set to os.Stdout and os.Stderr respectively. To redirect to both the console and a log file, modify the code as follows:
<code class="go">package main import ( "io" "log" "os" "os/exec" ) func main() { // Logging capability f, err := os.OpenFile("log.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) if err != nil { log.Fatalf("Error opening file: %v", err) } defer f.Close() mwriter := io.MultiWriter(f, os.Stdout) cmd := exec.Command("php", "randomcommand.php") cmd.Stdout = mwriter cmd.Stderr = mwriter if err := cmd.Run(); err != nil { log.Fatal(err) } }</code>
The mwriter variable is an instance of io.MultiWriter that contains both a log file and the standard output. By setting Stdout and Stderr of the command to this mwriter, the output of the command is written to both locations simultaneously.
The randomcommand.php script can remain the same, alternating between writing to stdout and stderr 20 times. When you run the Go program, the output will be printed to the console in real time and also logged to the specified log file, maintaining the exact order of writes to stdout and stderr.
The above is the detailed content of How to Redirect Command Output to Console and Log File Simultaneously in Go?. For more information, please follow other related articles on the PHP Chinese website!