Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the date/time format of Go's log package

Tags:

go

When using the log package, Go outputs something like

2009/11/10 23:00:00 Hello, world 

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") } 
like image 962
topskip Avatar asked Sep 30 '14 12:09

topskip


People also ask

How do I change time format in Golang?

Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time. Time object. We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows.

How can I get current date and time in go?

Using the “time. Now()” function you can get the date and time in the “yyyy-mm-dd hh:mm:ss. milliseconds timezone” format. This is simplest way for getting the date and time in golang.

How do you store dates in go?

For example, a 4-digit year might be represented by %Y . In Go, though, these parts of a date or time are represented by characters that represent a specific date. To include a 4-digit year in a Go date format, you would actually include 2006 in the string itself.

What does log fatal do in go?

log. Fatal makes use of os. Exit and is best called when an error is irreversible and may affect the entire program.


1 Answers

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!") } 

outputs:

2016-03-21T19:54:28.563Z [DEBUG] This is something being logged!

like image 191
clangager Avatar answered Sep 19 '22 08:09

clangager