Logrus时间戳格式化

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

Logrus timestamp formatting

问题

我正在尝试从Golang日志包转换到Logrus。我的问题是如何自定义记录消息的时间戳格式。默认格式是从启动开始计算的秒数,但我想要一个"2016-03-24 17:10:15"的格式。我的简单测试代码如下:

package main

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

func main() {
        customFormatter := new(logrus.TextFormatter)
        customFormatter.TimestampFormat = "2006-01-02 15:04:05"
        logrus.SetFormatter(customFormatter)
        logrus.Info("Hello Walrus")
}

这段代码可以编译和运行,但时间戳格式没有改变。有人可以解释一下为什么不起作用吗?

谢谢。

英文:

I'm trying to transition from the Golang log package to Logrus. My issue is around how to customize the timestamp format of logged messages. The default is a counter of seconds since start but I want a "2016-03-24 17:10:15" format. My simple test code is:

package main

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

func main() {
        customFormatter := new(logrus.TextFormatter)
        customFormatter.TimestampFormat = "2006-01-02 15:04:05"
        logrus.SetFormatter(customFormatter)
        logrus.Info("Hello Walrus")
}

This compiles and runs fine but the timestamp format is unchanged. Can anyone offer some insight into why it isn't working?

Thanks

答案1

得分: 41

我相信你想将以下字段设置为true,以便在使用TTY附加时启用时间戳。

根据logrus.TextFormatter的文档:

// 当TTY附加时,启用记录完整的时间戳,而不仅仅是自执行以来的时间。
FullTimestamp bool

调整你提供的示例:

package main

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

func main() {
    customFormatter := new(logrus.TextFormatter)
    customFormatter.TimestampFormat = "2006-01-02 15:04:05"
    logrus.SetFormatter(customFormatter)
    logrus.Info("Hello Walrus before FullTimestamp=true")
    customFormatter.FullTimestamp = true
    logrus.Info("Hello Walrus after FullTimestamp=true")
}

生成的输出:

$ go run main.go
INFO[0000] Hello Walrus before FullTimestamp=true
INFO[2016-03-24 20:18:56] Hello Walrus after FullTimestamp=true
英文:

I believe you want to set the following field to true to enable the timestamp when running it yourself with a TTY attached.

From the logrus.TextFormatter documentation:

// Enable logging the full timestamp when a TTY is attached instead of just
// the time passed since beginning of execution.
FullTimestamp bool

Tweaking your provided example:

package main

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

func main() {
    customFormatter := new(logrus.TextFormatter)
    customFormatter.TimestampFormat = "2006-01-02 15:04:05"
    logrus.SetFormatter(customFormatter)
    logrus.Info("Hello Walrus before FullTimestamp=true")
    customFormatter.FullTimestamp = true
    logrus.Info("Hello Walrus after FullTimestamp=true")
}

Produces:

$ go run main.go
INFO[0000] Hello Walrus before FullTimestamp=true
INFO[2016-03-24 20:18:56] Hello Walrus after FullTimestamp=true

huangapple
  • 本文由 发表于 2016年3月25日 01:17:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/36206187.html
匿名

发表评论

匿名网友

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

确定