How to Redirect Execution Output to a Logger in Real-time in Go?

Barbara Streisand
Release: 2024-11-08 01:59:02
Original
962 people have browsed it

How to Redirect Execution Output to a Logger in Real-time in Go?

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

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!

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