Home >Backend Development >Golang >How to Redirect Command Output to Both Console and Log File while Maintaining Order?

How to Redirect Command Output to Both Console and Log File while Maintaining Order?

DDD
DDDOriginal
2024-11-04 03:42:01192browse

How to Redirect Command Output to Both Console and Log File while Maintaining Order?

Redirecting Command Output to Console and Log File

To simultaneously display and log the stdout and stderr of a command while preserving output order, you can utilize the standard library's io.MultiWriter.

Code Snippet

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

Explanation

  1. Open a file for logging and create a MultiWriter that combines the file and standard output.
  2. Create a command and specify that both the stdout and stderr should use the MultiWriter.
  3. Execute the command, which will print output to both the console and log file in real-time while maintaining the original output order.

The above is the detailed content of How to Redirect Command Output to Both Console and Log File while Maintaining Order?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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