Problem:
When executing a process using exec.Command, how can you redirect its output to your log in real-time?
Context:
The conventional approach of waiting for the process to complete and then logging its combined output is not suitable for long-running or unfinished processes. Writing to stdout in real-time is also not helpful for services that don't use terminals.
Solution:
To capture and log process output in real-time, you can utilize pipes:
stdout, err := cmd.StdoutPipe() if err != nil { return 0, err } // Start the command after setting up the pipe if err := cmd.Start(); err != nil { return 0, err } // Read the command's stdout line by line in := bufio.NewScanner(stdout) for in.Scan() { log.Printf(in.Text()) // Log each line } if err := in.Err(); err != nil { log.Printf("error: %s", err) }
This approach allows you to capture both stdout and stderr by using a goroutine.
The above is the detailed content of How to Redirect Exec Command Output to Your Log in Real Time in Golang?. For more information, please follow other related articles on the PHP Chinese website!