Home > Article > Backend Development > How Do I Simultaneously Write Command Output to Console and Log File?
Writing Command Output to Console and Log File Simultaneously
You want to redirect output from a command to both the console and a log file. The existing code sends output to the console, but does not log it. To redirect both streams, use the technique described below.
To achieve your goals, consider the following approach:
Redirect Stdout and Stderr to a MultiWriter
Create a MultiWriter that combines the file and standard output. Then, before running the command, assign this MultiWriter to the command's Stdout and Stderr streams.
Example Code
<code class="go">package main import ( "io" "log" "os" "os/exec" ) func main() { // Open the log file for writing 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() // Create a MultiWriter that combines the log file and standard output mwriter := io.MultiWriter(f, os.Stdout) // Construct the command cmd := exec.Command("ls") // Redirect Stdout and Stderr to the MultiWriter cmd.Stdout = mwriter cmd.Stderr = mwriter // Run the command err = cmd.Run() if err != nil { panic(err) } }</code>
This code opens a log file, creates a MultiWriter, sets the command's streams to the MultiWriter, and runs the command. The output will be redirected to both the console and the log file in real-time and in the correct order.
The above is the detailed content of How Do I Simultaneously Write Command Output to Console and Log File?. For more information, please follow other related articles on the PHP Chinese website!