How to Redirect Exec Command Output to Your Log in Real Time in Golang?

Patricia Arquette
Release: 2024-11-17 12:38:01
Original
467 people have browsed it

How to Redirect Exec Command Output to Your Log in Real Time in Golang?

Golang: Copying Exec Output to Log

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)
}
Copy after login

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!

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