错误日志记录在哪里?

huangapple go评论76阅读模式
英文:

where does go log the errors?

问题

你好!根据你提供的信息,你正在使用Go语言的log包,并且想知道日志数据的默认目标位置。你想知道是否需要一个io writer,并在每个日志之后专门调用它,或者它应该如何工作。

在Go语言的log包中,默认的日志目标位置是标准错误输出(stderr)。也就是说,日志消息会被输出到控制台或终端窗口中。

你不需要显式地调用io writer来指定日志的目标位置,除非你想将日志消息写入到其他地方,比如文件或网络连接。如果你想将日志写入到文件中,你可以使用log包中的SetOutput函数来设置日志的目标位置为一个文件。

希望这个回答对你有帮助!如果你还有其他问题,请随时提问。

英文:

I'm using the log packages and I'm wondering what's the default destination of the log data. I can't find it anywhere. Do I need a io writer and specifically call it after each log or how is it supposed to work ?

答案1

得分: 6

应该是stdErr,在log.go的第58行中:

var std = New(os.Stderr, "", LstdFlags)

因此,像Fatal()这样的包方法默认使用std

// Fatal相当于Print()后调用os.Exit(1)。
func Fatal(v ...interface{}) {
    std.Output(2, fmt.Sprint(v...))
    os.Exit(1)
}

博客文章"如何编写程序员喜欢的Go包"(作者:Baron Schwartz)引用了这种技术:

> 我在标准Go库中发现的一种模式是我称之为“包和对象”。(这是我自己的名字;也许我正在重新发明或给另一个名字已知的东西命名。)你可以在几个包中看到这种习惯用法。它使得这些包非常好用。
>
> 这种习惯用法的本质是你像往常一样设计一个带有方法的类型,然后还在包级别本身放置匹配的函数。这些函数只是简单地委托给一个默认的类型实例,该实例是一个私有的包级别变量,在init()函数中创建
>
> 例如,要查看默认的日志功能,你只需导入log包,然后编写log.Print()之类的代码。它非常简洁和方便,并且会做正确的事情。
想要自定义它?创建自己的log.Logger变量,并设置其属性。


请注意,从Go 1.13(2019年第三季度)开始,新的Writer()函数返回标准记录器的输出目标。

英文:

It should be stdErr, as in line 58 of log.go:

var std = New(os.Stderr, "", LstdFlags)

So package methods like Fatal() uses std by default:

// Fatal is equivalent to Print() followed by a call to os.Exit(1).
func Fatal(v ...interface{}) {
    std.Output(2, fmt.Sprint(v...))
    os.Exit(1)
}

The blog post "How to write Go packages coders will love " (by Baron Schwartz) references that technique:

> One of the patterns I've found in the standard Go library is what I call package-and-object. (That's my own name; maybe I'm reinventing or naming something already known by another name.) You can see this idiom in several packages. It makes these packages a delight to use.
>
> The essence of the idiom is that you design a type with methods as usual, and then you also place matching functions at the package level itself. These functions simply delegate to a default instance of the type that's a private package-level variable, created in an init() function.
>
> To take a look at the default logging functionality, for example, you can just import the log package and then write things like log.Print(). It's super-concise and handy, and it does the right thing.
Want to customize it? Make your own log.Logger variable, and set its properties.


Note that, with Go 1.13 (Q3 2019), the new Writer() function returns the output destination for the standard logger.

huangapple
  • 本文由 发表于 2014年5月9日 08:00:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/23554647.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定