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") }
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.
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.
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.
log. Fatal makes use of os. Exit and is best called when an error is irreversible and may affect the entire program.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With