Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print message to stderr in Go?

Tags:

linux

go

I want to print some logs for debugging and testing, but existing logs are massive, so I want to print my own logs to stderr:

go run main.go 1>/dev/null

So that I can just see my own logs.

How can I do that?

like image 443
kaitian521 Avatar asked Mar 09 '15 03:03

kaitian521


2 Answers

There are multiple methods to send a message to stderr:

  1. Creating a new log.Logger:

    l := log.New(os.Stderr, "", 1)
    l.Println("log message")
    
  2. Using fmt.Fprintf:

    fmt.Fprintf(os.Stderr, "log message: %s", str)
    
  3. Directly writing to os.Stderr using os.Stderr.WriteString:

    os.Stderr.WriteString("log message")
    
like image 171
Nikhita Raghunath Avatar answered Sep 18 '22 12:09

Nikhita Raghunath


The log package by default prints to os.Stderr.

You can also use os.Stderr directly (it's an os.File).

like image 22
OneOfOne Avatar answered Sep 16 '22 12:09

OneOfOne