How can I set the logrus time to UTC

huangapple go评论91阅读模式
英文:

How can I set the logrus time to UTC

问题

我正在使用logrus的Go语言库,但是我发现时间字段总是以本地时间格式化。我该如何将时间更改为logrus的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

答案1

得分: 11

时区设置不支持直接操作,但是你可以使用自定义的 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"}
英文:

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

答案2

得分: 1

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

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

源代码

英文:

You need to write your own implimentation of logrus.Formatter.

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

Source

huangapple
  • 本文由 发表于 2016年11月9日 16:03:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/40502309.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定