Home >Backend Development >Golang >How to Redirect Command Output to Both Console and Log File while Maintaining Order?
To simultaneously display and log the stdout and stderr of a command while preserving output order, you can utilize the standard library's io.MultiWriter.
<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("ls") cmd.Stderr = mwriter cmd.Stdout = mwriter err = cmd.Run() //blocks until sub process is complete if err != nil { panic(err) } }</code>
The above is the detailed content of How to Redirect Command Output to Both Console and Log File while Maintaining Order?. For more information, please follow other related articles on the PHP Chinese website!