英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论