Logrus时间戳格式化

Ste*_*ook 12 logging go

我正在尝试从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")
}
Run Code Online (Sandbox Code Playgroud)

这编译并运行正常,但时间戳格式保持不变.任何人都可以提供一些有关它不工作原因的见解吗?

谢谢

小智 19

我相信您要将以下字段设置为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
Run Code Online (Sandbox Code Playgroud)

调整您提供的示例:

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")
}
Run Code Online (Sandbox Code Playgroud)

生产:

$ go run main.go
INFO[0000] Hello Walrus before FullTimestamp=true
INFO[2016-03-24 20:18:56] Hello Walrus after FullTimestamp=true
Run Code Online (Sandbox Code Playgroud)

  • 作为一句: `logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: "2006-01-02 15:04:05", FullTimestamp: true})` (7认同)
  • Golang 的时间格式化疯狂是使用所谓的“参考日期”作为模板,因此必须从字面上使用“2006-01-02”而不是“YYYY-MM-DD”。另见 /sf/ask/1416387311/ (5认同)
  • 为什么使用该特定日期?任何其他相同格式的日期都会导致奇怪的结果。与 2007 相同的日期给了我 3007 作为当前年份。 (3认同)