简体   繁体   English

如何在 Go 中将消息打印到 stderr?

[英]How do I print message to stderr in 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:我想打印一些日志用于调试和测试,但是现有的日志很大,所以我想将自己的日志打印到stderr:

go run main.go 1>/dev/null

So that I can just see my own logs.这样我就可以看到我自己的日志。

How can I do that?我怎样才能做到这一点?

There are multiple methods to send a message to stderr :有多种方法可以向stderr发送消息:

  1. Creating a new log.Logger :创建一个新的log.Logger

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

     fmt.Fprintf(os.Stderr, "log message: %s", str)
  3. Directly writing to os.Stderr using os.Stderr.WriteString :直接写入os.Stderr使用os.Stderr.WriteString

     os.Stderr.WriteString("log message")

The log package by default prints to os.Stderr . log默认打印到os.Stderr

You can also use os.Stderr directly (it's an os.File ).您也可以直接使用os.Stderr (它是一个os.File )。

On Linux systems, you could also use syslog(3) facilities.在 Linux 系统上,您还可以使用syslog(3)工具。 By default, the underlying openlog(3) does not go to stderr, but this can be changed.默认情况下,底层的openlog(3)不会转到 stderr,但这可以更改。

See Go package log/syslog .请参阅 Go 包日志/系统日志

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM