Search code examples
gotime-format

How can I set the logrus time to UTC


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


Solution

  • 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"}