How do I print message to stderr in Go?

前端 未结 3 798
臣服心动
臣服心动 2021-01-04 06:50

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
<         


        
相关标签:
3条回答
  • 2021-01-04 07:07

    The log package by default prints to os.Stderr.

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

    0 讨论(0)
  • 2021-01-04 07:19

    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")
      
    0 讨论(0)
  • 2021-01-04 07:29

    On Linux systems, you could also use syslog(3) facilities. By default, the underlying openlog(3) does not go to stderr, but this can be changed.

    See Go package log/syslog.

    0 讨论(0)
提交回复
热议问题