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

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

问题描述:

How can I write a message to Stderr without using log?

A comment in this SO post shows how to do it with log: log.Println("Message"), but what if I don't want a timestamp?

Is the following good Go?

os.Stderr.WriteString("Message")

如何在不使用 log code>的情况下向Stderr写消息? p> \ n

在此SO帖子中的评论 显示了如何使用 log code>: log.Println(“ Message”) code>,但是如果我不想使用时间戳怎么办? p>

以下是不错的Go吗? p>

os.Stderr.WriteString(“ Message”) code> p> div>

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)

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.

By default the logger flags are set to Ldate | Ltime. You can change the logger format to any of the following (from the 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

For example, flags Ldate | Ltime (or LstdFlags) produce,

2009/01/23 01:23:23 message

While flags Ldate | Ltime | Lmicroseconds | Llongfile produce,

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

You can also set the default logger to not print anything by setting the flag to 0:

log.SetFlags(0)

use SetOutput function, set output stream to os.Stdout

import (
    "log"
    "os"
)

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

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