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

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!


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.


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)).

Tags:

Go