Writing to stderr in golang - the simple way

169 Views Asked by At

I am looking to write to stderr; to write to stdout, this works:

fmt.Println(...)

Is there a better way to write to stderr than this:

 _, err := fmt.Fprintln(os.Stderr, "This is an error message")
    if err != nil {
        panic(err) // Handle the error appropriately in your application
    }

seems weird that there is no simple API for this.

1

There are 1 best solutions below

0
River Cartwright On

It is common for applications to ignore the error return from fmt.Fprintln(os.Stderr, ...), just as it's common for applications ignore the error returned from fmt.Println(...).

That is, it's common to write:

fmt.Fprintln(os.Stderr, "This is an error message")

instead of the code in the question.

It is also common to use the log package to write to stderr (the standard logger writes to stderr by default).

If os.Stderr is a pipe and the pipe is closed, then calls to fmt.Fprintln(os.Stderr, ...) will cause the application to exit with signal SIGPIPE.