Anton Lindstrom (about, @twitter, @github)

Capture stdout in Golang

Published:

Working with Docker and Golang for a hobby project, I needed to get the output from docker build into my own log function. To do this, it's pretty easy do some redirections to solve this:

func RedirectOutput(id string) {
        oldStdout := os.Stdout
        readFile, writeFile, err := os.Pipe()
        if err != nil {
                return err
        }

        os.Stdout = writeFile

        go func() {
                scanner := bufio.NewScanner(r)
                for scanner.Scan() {
                        line := scanner.Text()

                        // Log the stdout line to my event logger
                        event.Log(event.Event{Id: id, Msg: line})
                }
        }()

        fmt.Printf("This will be logged to our event logger\n")

        // Reset the output again
        writeFile.Close()
        os.Stdout = oldStdout
}

The function will log everything printed to stdout line by line to our event logger. This can be used to override fmt.Printf and sending it to your own logger without having to import a package in every file.

My event logger stores events in a simple Redis database so I can look at them later. This was a really simple way to solve that.