【问题标题】:Logrus timestamp formattingLogrus 时间戳格式
【发布时间】:2016-07-12 09:32:42
【问题描述】:

我正在尝试从 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")
}

这编译并运行良好,但时间戳格式未更改。谁能提供一些关于它为什么不起作用的见解?

谢谢

【问题讨论】:

    标签: logging go


    【解决方案1】:

    我相信您希望将以下字段设置为 true 以在附加 TTY 的情况下自行运行时启用时间戳。

    来自logrus.TextFormatter 文档:

    // Enable logging the full timestamp when a TTY is attached instead of just
    // the time passed since beginning of execution.
    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
    

    【讨论】:

    • 为什么要使用那个特定的日期?相同格式的任何其他日期都会导致奇怪的结果。与 2007 年相同的日期给我 3007 作为当年。
    • Golang 的时间格式化疯狂是使用所谓的“参考日期”作为模板,因此必须使用“2006-01-02”字面意思来代替“YYYY-MM-DD”。另见stackoverflow.com/questions/20234104
    • 单线:logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: "2006-01-02 15:04:05", FullTimestamp: true})
    猜你喜欢
    • 1970-01-01
    • 2011-12-04
    • 2019-02-17
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多