How can I redirect the stdout and stderr of a command to both the console and a log file while outputting in real time?

后端 未结 1 972
感情败类
感情败类 2021-01-01 03:56

The following bit of code does exactly what I want, except it only prints to the console.

cmd := exec.Command(\"php\", \"randomcommand.php\")

cmd.Stdout =          


        
相关标签:
1条回答
  • 2021-01-01 04:08

    As I said in the comment section, this can be achieved using MultiWriter

    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("ls")
        cmd.Stderr = mwriter
        cmd.Stdout = mwriter
        err = cmd.Run() //blocks until sub process is complete
        if err != nil {
            panic(err)
        }
    }
    

    When you declare your command, and before you run it, just specify that Stdout and Stderr are using the MultiWriter defined above. This MultiWriter instance contains both a log file and the standard output.

    0 讨论(0)
提交回复
热议问题