Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the logrus time to UTC

Tags:

time-format

go

I am using Go with logrus, however I found the time field is always formatted in local time. How can I change the time to UTC time for logrus?

Thanks

like image 229
want_to_be_calm Avatar asked Nov 09 '16 08:11

want_to_be_calm


1 Answers

Time zone setting is not supported directly, but you may use a custom log.Formatter in which you may "switch" to the time zone of your choice, UTC included.

A simple usage that uses the local time zone (not UTC) may look like this:

import (
    log "github.com/Sirupsen/logrus"
)

func main() {
    log.SetFormatter(&log.JSONFormatter{})
    log.Info("Testing")
}

Output (time is formatted using my +01 local timezone):

{"level":"info","msg":"Testing","time":"2016-11-09T09:28:02+01:00"}

Now let's create a custom log.Formatter which switches to UTC:

type UTCFormatter struct {
    log.Formatter
}

func (u UTCFormatter) Format(e *log.Entry) ([]byte, error) {
    e.Time = e.Time.UTC()
    return u.Formatter.Format(e)
}

func main() {
    log.SetFormatter(UTCFormatter{&log.JSONFormatter{}})
    log.Info("Testing")
}

Output (time is formatted in UTC timezone):

{"level":"info","msg":"Testing","time":"2016-11-09T08:28:09Z"}
like image 168
icza Avatar answered Sep 21 '22 07:09

icza