Home > Backend Development > Golang > How to Redirect Command Output to a Log in Real-Time in Golang?

How to Redirect Command Output to a Log in Real-Time in Golang?

Mary-Kate Olsen
Release: 2024-11-12 13:38:02
Original
697 people have browsed it

How to Redirect Command Output to a Log in Real-Time in Golang?

Redirecting Command Output to Log 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)
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template