如何在不使用日志的情况下打印到 Go 中的 Stderr

How can I print to Stderr in Go without using log

如何在不使用 log 的情况下将消息写入 Stderr?

展示了如何使用 loglog.Println("Message"),但是如果我不想要时间戳怎么办?

下面的围棋好吗?

os.Stderr.WriteString("Message")

如果您不需要时间戳,只需创建一个新的 log.Logger 并将 flag 设置为 0:

l := log.New(os.Stderr, "", 0)
l.Println("log msg")

编辑:

Is the following good Go?

os.Stderr.WriteString("Message")

这是可以接受的,你也可以使用fmt.Fprintf和朋友来获得格式化输出:

fmt.Fprintf(os.Stderr, "number of foo: %d", nFoo)

使用 fmt 包,您可以选择这样写入 stderr

import "fmt"
import "os"

func main() {
    fmt.Fprintln(os.Stderr, "hello world")
}

os.Stderr is an io.Writer,因此您可以在任何接受 io.Writer 的函数中使用它。这里有几个例子:

str := "Message"
fmt.Fprintln(os.Stderr, str)
io.WriteString(os.Stderr, str)
io.Copy(os.Stderr, bytes.NewBufferString(str))
os.Stderr.Write([]byte(str))

这完全取决于您拥有要打印的字符串的准确程度(即,如果您想先格式化它,如果您将它作为 io.Reader,如果您将它作为字节切片。 ..).而且可以有更多的方法。

默认情况下,记录器标志设置为 Ldate | Ltime。您可以将记录器格式更改为以下任何格式(来自 golang log documentation):

Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
Ltime                         // the time in the local time zone: 01:23:23
Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
Llongfile                     // full file name and line number: /a/b/c/d.go:23
Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
LstdFlags     = Ldate | Ltime // initial values for the standard logger

例如,标记 Ldate | Ltime(或 LstdFlags)产生,

2009/01/23 01:23:23 message

同时标记 Ldate |时间 | L微秒 | Llongfile 产品,

2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message

您还可以通过将标志设置为 0 来将默认记录器设置为不打印任何内容:

log.SetFlags(0)

使用SetOutput函数,设置输出流为os.Stdout

import (
    "log"
    "os"
)

func init() {
    log.SetOutput(os.Stdout)
}

func main() {
    log.Println("Gene Story SNP File Storage Server Started.")
}

Go 内置函数 printprintln 打印到标准错误。所以如果你只是想输出一些文本到 stderr 你可以做

package main

func main() {
    println("Hello stderr!")
}

文档:https://golang.org/pkg/builtin/#print