Redirecting Execution Output to Logger in Go
In Go, the exec package provides mechanisms for executing external commands. While the CombinedOutput method can capture the entire output once the command finishes, it may not be suitable for long-running or unfinished processes.
To redirect the output of a command to a logger in real-time, a more flexible approach is required. One technique involves using a pipe to connect the command's output to the logger.
Here's an example code snippet:
import ( "bufio" "log" "os/exec" ) func main() { cmd := exec.Command("yes") // Create a pipe to connect the command's stdout to the logger stdout, err := cmd.StdoutPipe() if err != nil { log.Fatalf("Failed to create stdout pipe: %v", err) } // Start the command if err := cmd.Start(); err != nil { log.Fatalf("Failed to start command: %v", err) } // Create a buffered reader to read the output line by line in := bufio.NewScanner(stdout) // Read the output and log it in real-time for in.Scan() { log.Printf(in.Text()) } if err := in.Err(); err != nil { log.Printf("Error reading command output: %v", err) } }
In this example, the Stderr stream can also be handled concurrently by creating a separate goroutine. By piping the command's output to the logger, developers can capture and log its real-time output, making it easier to monitor and troubleshoot processes in their applications.
The above is the detailed content of How to Redirect Execution Output to a Logger in Real-time in Go?. For more information, please follow other related articles on the PHP Chinese website!