How can I print to Stderr in Go without using log
The Go builtin functions print
and println
print to stderr. So if you simply want to output some text to stderr you can do
package main
func main() {
println("Hello stderr!")
}
Documentation: https://golang.org/pkg/builtin/#print
Using the fmt
package, you can choose to write to stderr
this way:
import "fmt"
import "os"
func main() {
fmt.Fprintln(os.Stderr, "hello world")
}
os.Stderr
is an io.Writer
, so you can use it in any function which accepts an io.Writer
. Here are a few examples:
str := "Message"
fmt.Fprintln(os.Stderr, str)
io.WriteString(os.Stderr, str)
io.Copy(os.Stderr, bytes.NewBufferString(str))
os.Stderr.Write([]byte(str))
It all depends on how exactly you have the string you want to print (i.e. if you want to format it first, if you have it as an io.Reader
, if you have it as a byte slice...). And there can be a lot more ways.
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)