How to redirect stderr to file

I’m trying to rediect standardout and standarderr to file, I can redirect standard out to file by overwriting

os.Stdout = *os.File

But when I’m trying to do the same with os.Stderr its not taking in effect, errors and other panics are still printing in console.

Can you redirect stderr and stdout from wherever you start your go program instead of within the Go program? E.g.:

./mygoprogram > /var/log/mygoprogram.stdout.log 2> /var/log/mygoprogram.stderr.log

So I need to write a bash program to automate this process?

I’m not saying it’s your only option, just that it seems like a better option than changing os.Stdout and/or os.Stderr. There might be some initialization in some package somewhere that caches the value of os.Stdout before you change it; for example:

package "somepackage"

var someKindOfLogger = &logger{
    writer: os.Stderr,
    // ...
}

func logSomethingOnPanic() {
    someKindOfLogger.WriteSomething() // uses someKindOfLogger.writer which is
        // the value of os.Stderr before you changed it.
}
package "main"

func main() {
    os.Stderr = createStderrReplacementFile() // this doesn't help because other
        // init code already cached the value of os.Stderr somewhere.
    doSomethingThatPanics()
}

If you redirect stderr and stdout, there is no timing issue related to changing os.Stdout before or after it’s been cached somewhere.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.