的日期/時間格式在使用log package,去輸出像如何更改Go的日誌包
2009/11/10 23:00:00 Hello, world
如何更改日期和時間格式爲類似dd.mm.yyy hh:mm:ss
?示例(playground link):
package main
import "log"
func main() {
log.Println("Hello, playground")
}
的日期/時間格式在使用log package,去輸出像如何更改Go的日誌包
2009/11/10 23:00:00 Hello, world
如何更改日期和時間格式爲類似dd.mm.yyy hh:mm:ss
?示例(playground link):
package main
import "log"
func main() {
log.Println("Hello, playground")
}
像yed posterior說的,你可以通過實現一個寫函數來定義一個自定義的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!")
}
輸出:
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
你需要使用第三方軟件包內,或截取所描述的日誌輸出。
使用自定義編寫器來過濾日誌行以將其修改爲您需要的格式。這應該很簡單,因爲標題的格式是固定寬度和固定寬度。然後調用log.SetOutput(myFilterWriter(os.Stderr))。
謝謝 - 我恐怕我必須接受這個答案:) – topskip 2014-09-30 12:37:58