Copying Exec Output to Log in Go
In Go, redirecting the output of a long-running or non-finishing process to a log can be challenging. While waiting for the process to complete allows for simple output capture, real-time logging in non-terminal environments requires a different approach.
One solution involves creating a pipe to connect the process's stdout to a buffered scanner:
stdout, err := cmd.StdoutPipe() if err != nil { return 0, err } // start the command after having set up the pipe if err := cmd.Start(); err != nil { return 0, err } // read command's stdout line by line in := bufio.NewScanner(stdout) for in.Scan() { log.Printf(in.Text()) // write each line to your log, or anything you need } if err := in.Err(); err != nil { log.Printf("error: %s", err) }
This code creates a stdout pipe, starts the command, and then uses a scanner to read the output line by line. Each line can then be logged or processed as needed. By handling Stdout in this way, you can redirect the process's output to your log while it is still running, ensuring timely logging of important information for your service.
The above is the detailed content of How to Redirect Exec Output to a Log in Go?. For more information, please follow other related articles on the PHP Chinese website!