【问题标题】:How can I set the logrus time to UTC如何将 logrus 时间设置为 UTC
【发布时间】:2017-03-22 23:43:04
【问题描述】:

我将 Go 与 logrus 一起使用,但我发现时间字段始终以当地时间格式化。如何将 logrus 的时间更改为 UTC 时间?

谢谢

【问题讨论】:

    标签: go time-format


    【解决方案1】:

    不直接支持时区设置,但您可以使用自定义log.Formatter,您可以在其中“切换”到您选择的时区,包括UTC。

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

    import (
        log "github.com/Sirupsen/logrus"
    )
    
    func main() {
        log.SetFormatter(&log.JSONFormatter{})
        log.Info("Testing")
    }
    

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

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

    现在让我们创建一个自定义的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")
    }
    

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

    {"level":"info","msg":"Testing","time":"2016-11-09T08:28:09Z"}
    

    【讨论】:

    • 太干净了。我喜欢它。
    【解决方案2】:

    你需要自己编写logrus.Formatter的实现。

    type Formatter interface {
        Format(*Entry) ([]byte, error)
    }
    

    Source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-10
      • 2018-10-04
      • 2020-05-10
      • 1970-01-01
      • 2016-06-01
      • 2018-09-13
      • 1970-01-01
      • 2018-05-19
      相关资源
      最近更新 更多