Home > Article > Backend Development > How to Simultaneously Log and Print Command Output to Console?
Simultaneous Console and Log Output for Command Stdout and Stderr
The goal of the provided code is to print command stdout and stderr to the console in real-time while simultaneously logging them to a file in console order, without modifying the command itself.
To achieve this, we can utilize the io.MultiWriter type. Here's how:
<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() // Define a MultiWriter that includes both the log file and stdout multiWriter := io.MultiWriter(f, os.Stdout) // Set stdout and stderr of the command to the MultiWriter cmd := exec.Command("php", "randomcommand.php") cmd.Stdout = multiWriter cmd.Stderr = multiWriter if err := cmd.Run(); err != nil { log.Fatal(err) } }</code>
By defining multiWriter as a combination of the log file and stdout, we effectively write command output to both destinations simultaneously. cmd.Run() blocks until the command completes, ensuring output order is maintained.
This solution satisfies all requirements:
The above is the detailed content of How to Simultaneously Log and Print Command Output to Console?. For more information, please follow other related articles on the PHP Chinese website!