如何将logrus时间设置为UTC

wan*_*alm 3 time-format go

我正在使用Go with logrus,但我发现时间字段始终以本地时间格式化.如何将logrus的时间更改为UTC时间?

谢谢

icz*_*cza 7

时区设置不是直接支持,但您可以使用自定义log.Formatter"切换"到您选择的时区(包括UTC).

使用本地时区(不是UTC)的简单用法可能如下所示:

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

func main() {
    log.SetFormatter(&log.JSONFormatter{})
    log.Info("Testing")
}
Run Code Online (Sandbox Code Playgroud)

输出(时间使用我的+01本地时区格式化):

{"level":"info","msg":"Testing","time":"2016-11-09T09:28:02+01:00"}
Run Code Online (Sandbox Code Playgroud)

现在让我们创建一个log.Formatter切换到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")
}
Run Code Online (Sandbox Code Playgroud)

输出(时间格式为UTC时区):

{"level":"info","msg":"Testing","time":"2016-11-09T08:28:09Z"}
Run Code Online (Sandbox Code Playgroud)

  • 那太干净了.我喜欢它. (2认同)