Home >Backend Development >Golang >How to Simultaneously Log and Print Command Output to Console?

How to Simultaneously Log and Print Command Output to Console?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-04 01:12:02529browse

How to Simultaneously Log and Print Command Output to Console?

Simultaneous Console and Log Output for Command Stdout and Stderr

The goal of the provided code is to print command stdout and stderr to the console in real-time while simultaneously logging them to a file in console order, without modifying the command itself.

To achieve this, we can utilize the io.MultiWriter type. Here's how:

<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()

    // Define a MultiWriter that includes both the log file and stdout
    multiWriter := io.MultiWriter(f, os.Stdout)

    // Set stdout and stderr of the command to the MultiWriter
    cmd := exec.Command("php", "randomcommand.php")
    cmd.Stdout = multiWriter
    cmd.Stderr = multiWriter

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

By defining multiWriter as a combination of the log file and stdout, we effectively write command output to both destinations simultaneously. cmd.Run() blocks until the command completes, ensuring output order is maintained.

This solution satisfies all requirements:

  • Prints stdout and stderr to the console in real-time.
  • Logs stdout and stderr to a file, mirroring console output.
  • Respects the exact order of writes to stdout and stderr.
  • Does not modify the command itself.

The above is the detailed content of How to Simultaneously Log and Print Command Output to Console?. 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