How to Redirect Command Output to Console and Log File Simultaneously in Go?

Susan Sarandon
Release: 2024-11-03 22:07:30
Original
982 people have browsed it

How to Redirect Command Output to Console and Log File Simultaneously in Go?

Redirecting Command Output to Console and Log File Simultaneously

To redirect the stdout and stderr of a command to both the console and a log file in real time, you can employ the io.MultiWriter type in Go. Here's how:

In the code snippet provided, the code redirects only to the console because the Stdout and Stderr fields of the cmd are set to os.Stdout and os.Stderr respectively. To redirect to both the console and a log file, modify the code as follows:

<code class="go">package main

import (
    "io"
    "log"
    "os"
    "os/exec"
)

func main() {
    // Logging capability
    f, err := os.OpenFile("log.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
    if err != nil {
        log.Fatalf("Error opening file: %v", err)
    }
    defer f.Close()
    mwriter := io.MultiWriter(f, os.Stdout)

    cmd := exec.Command("php", "randomcommand.php")
    cmd.Stdout = mwriter
    cmd.Stderr = mwriter

    if err := cmd.Run(); err != nil {
        log.Fatal(err)
    }
}</code>
Copy after login

The mwriter variable is an instance of io.MultiWriter that contains both a log file and the standard output. By setting Stdout and Stderr of the command to this mwriter, the output of the command is written to both locations simultaneously.

The randomcommand.php script can remain the same, alternating between writing to stdout and stderr 20 times. When you run the Go program, the output will be printed to the console in real time and also logged to the specified log file, maintaining the exact order of writes to stdout and stderr.

The above is the detailed content of How to Redirect Command Output to Console and Log File Simultaneously 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!