Reputation: 17335
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")
}
Upvotes: 39
Views: 30574
Reputation: 628
It's much easier to use the flags from Logger system internal.
log.SetFlags(log.Lmicroseconds)
Use this flag to add timestamp with microseconds to the log. Other available options are :
const (
Ldate = 1 << iota // the date in the local time zone: 2009/01/23
Ltime // the time in the local time zone: 01:23:23
Lmicroseconds // microsecond resolution: 01:23:23.123123. assumes Ltime.
Llongfile // full file name and line number: /a/b/c/d.go:23
Lshortfile // final file name element and line number: d.go:23. overrides Llongfile
LUTC // if Ldate or Ltime is set, use UTC rather than the local time zone
Lmsgprefix // move the "prefix" from the beginning of the line to before the message
LstdFlags = Ldate | Ltime // initial values for the standard logger
)
Golang logger documentation is available here
Upvotes: 1
Reputation: 1013
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!
Upvotes: 71
Reputation: 25732
According to the source (http://golang.org/src/pkg/log/log.go) there is no built-in way to do that:
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
You'll need to use a 3rd party package for that, or intercept the log output as yed described.
Upvotes: 6
Reputation: 51
Use a custom writer that filters the log lines to modify them to the format you need. It should be easy because the format of the header is regular and fixed-width. Then call log.SetOutput(myFilterWriter(os.Stderr)).
Upvotes: 5