Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print to Stderr in Go without using log

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")

like image 382
Max Heiber Avatar asked Apr 18 '15 18:04

Max Heiber


People also ask

Should logs go to stderr?

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.

When can I print to stderr?

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.

What is stdout in Golang?

stdout is a file that is printed immediately to the screen by the console. // See all fmt.print function fmt. Println("Bouh") Go.


1 Answers

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) 
like image 197
Ainar-G Avatar answered Oct 09 '22 02:10

Ainar-G