Redirect os.Stderr in Go

This is an example Go program which indicates how to redirect os.Stderr.

package main

import (
        "fmt"
        "os"
)

func main() {
        newstderr, err := os.Create("rs.txt")
        if err != nil {
                fmt.Fprintf(os.Stderr, "Error %s\n", err)
                os.Exit(1)
        }
        defer newstderr.Close()
        os.Stderr.Close()
        os.Stderr = newstderr
        fmt.Fprintf(newstderr, "He'll think about paint, and he'll think about glue\n")
        fmt.Fprintf(os.Stderr, "What a jolly boring thing to do\n")
}

(download)

The output of the example looks like this:

He'll think about paint, and he'll think about glue
What a jolly boring thing to do

Redirecting the output of log

However, this doesn't redirect the output of log, which apparently copies os.Stderr at initialisation. To redirect the output of log, you need to use log.SetOutput.

package main

import (
        "fmt"
        "log"
        "os"
)

func main() {
        newstderr, err := os.Create("rslog.txt")
        if err != nil {
                fmt.Fprintf(os.Stderr, "Error %s\n", err)
                os.Exit(1)
        }
        defer newstderr.Close()
        log.SetOutput(newstderr)
        log.Fatal("Andy Warhol, silver screen, can't tell them apart at all")
}

(download)

This puts the output of log.Fatal into the file rslog.txt.

Redirecting the output of panic

Incidentally, there is absolutely no way whatsoever within the Go language to redirect the output of panic, so you absolutely must write your own recover routine, otherwise the output will go to whatever the operating system's standard error is, completely regardless of the value of os.Stderr. This is by design.



Copyright © Ben Bullock 2009-2023. All rights reserved. For comments, questions, and corrections, please email Ben Bullock (benkasminbullock@gmail.com) or use the discussion group at Google Groups. / Privacy / Disclaimer