使用日志包时,Go会输出类似的内容
2009/11/10 23:00:00 Hello, world
Run Code Online (Sandbox Code Playgroud)
如何将日期和时间格式更改为类似的内容dd.mm.yyy hh:mm:ss?示例(游乐场链接):
package main
import "log"
func main() {
log.Println("Hello, playground")
}
Run Code Online (Sandbox Code Playgroud)
小智 30
就像后面所说的那样,你可以通过实现一个写函数来定义一个自定义的io.Writer.你也可能想做一个log.SetFlags(0)来完全控制.这是一个更改日期格式以及添加一些日志级别信息的示例.
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!")
}
Run Code Online (Sandbox Code Playgroud)
输出:
2016-03-21T19:54:28.563Z [DEBUG]这是记录的内容!
根据来源(http://golang.org/src/pkg/log/log.go)没有内置的方法来做到这一点:
26 // Bits or'ed together to control what's printed. There is no control over the
27 // order they appear (the order listed here) or the format they present (as
28 // described in the comments). A colon appears after these items:
29 // 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
Run Code Online (Sandbox Code Playgroud)
您需要为此使用 3rd 方包,或者按照 yed 的描述拦截日志输出。
小智 5
使用自定义编写器来过滤日志行,将其修改为您需要的格式。这应该很容易,因为标头的格式是常规且固定宽度的。然后调用 log.SetOutput(myFilterWriter(os.Stderr))。