Home >Backend Development >Golang >How to Redirect Command Output to a Log in Real-Time in Golang?
When executing a command using the exec.Command function, it is often desirable to redirect the output to a log for real-time monitoring. While CombinedOutput can capture the entire output once the command finishes, it is not suitable for long-running or unfinished processes.
A common solution for real-time output redirection is to directly assign stdout and stderr to system output streams (os.Stdout and os.Stderr). However, this may not be practical for applications that do not write to a terminal.
Solution Using Pipes
To redirect command output to a log, you can utilize pipes. Here is an example:
stdout, err := cmd.StdoutPipe() if err != nil { return nil, err } // Start the command with the pipe in place if err := cmd.Start(); err != nil { return nil, err } // Real-time monitoring of stdout in := bufio.NewScanner(stdout) for in.Scan() { log.Printf(in.Text()) // Write line to log or perform other operations } if err := in.Err(); err != nil { log.Printf("Error: %s", err) }
Considerations
This method handles stdout, but you can also manage stderr by creating a separate pipe and goroutine. Additionally, you may need to handle context cancellation or other edge cases to ensure proper cleanup and resource management.
The above is the detailed content of How to Redirect Command Output to a Log in Real-Time in Golang?. For more information, please follow other related articles on the PHP Chinese website!