如何更改Go日志包的日期/时间格式 [英] How to change the date/time format of Go's log package
本文介绍了如何更改Go日志包的日期/时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用日志包时,Go会输出类似
When using the log package, Go outputs something like
2009/11/10 23:00:00 Hello, world
如何将日期和时间格式更改为 dd.mm.yyy hh:mm:ss
?示例(游乐场链接):
How can I change the date and time format to something like dd.mm.yyy hh:mm:ss
? Example (playground link):
package main
import "log"
func main() {
log.Println("Hello, playground")
}
推荐答案
就像后述的那样,您可以通过实现write函数来定义自定义io.Writer.您可能还想做一个log.SetFlags(0)来完全控制.这是一个更改日期格式并添加一些日志级别信息的示例.
Like yed posterior said, you can define a custom io.Writer by implementing a write function. You'll also probably want to do a log.SetFlags(0) to take full control. Here's an example that changes the date format as well as adds some log level info.
type logWriter struct {
}
func (writer logWriter) Write(bytes []byte) (int, error) {
return fmt.Print(time.Now().UTC().Format("2006-01-02T15:04:05.999Z") + " [DEBUG] " + string(bytes))
}
func main() {
log.SetFlags(0)
log.SetOutput(new(logWriter))
log.Println("This is something being logged!")
}
输出:
2016-03-21T19:54:28.563Z [DEBUG]这已被记录!
2016-03-21T19:54:28.563Z [DEBUG] This is something being logged!
这篇关于如何更改Go日志包的日期/时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文