How can I write a message to Stderr without using log
?
A comment in this SO post shows how to do it with log
: log.Println("Message")
, but what if I don't want a timestamp?
Is the following good Go?
os.Stderr.WriteString("Message")
Only error logs should go to stderr. This is a pretty common convention supported by the 12factor design principles and the original intent behind io streams in operating systems. With all logs dumped to stderr, it's significantly more difficult to sift through output from using pipes.
It is good practice to redirect all error messages to stderr , while directing regular output to stdout . It is beneficial to do this because anything written to stderr is not buffered, i.e., it is immediately written to the screen so that the user can be warned immediately.
stdout is a file that is printed immediately to the screen by the console. // See all fmt.print function fmt. Println("Bouh") Go.
If you don't want timestamps, just create a new log.Logger
with flag
set to 0
:
l := log.New(os.Stderr, "", 0) l.Println("log msg")
EDIT:
Is the following good Go?
os.Stderr.WriteString("Message")
This is acceptable, and you can also use fmt.Fprintf
and friends to get formatted output:
fmt.Fprintf(os.Stderr, "number of foo: %d", nFoo)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With