【问题标题】:How to change the date/time format of Go's log package如何更改 Go 的日志包的日期/时间格式
【发布时间】:2014-09-30 12:19:56
【问题描述】:

当使用log package 时,Go 会输出类似

2009/11/10 23:00:00 Hello, world

如何将日期和时间格式更改为dd.mm.yyy hh:mm:ss 之类的格式?示例(playground link):

package main

import "log"

func main() {
    log.Println("Hello, playground")
}

【问题讨论】:

    标签: go


    【解决方案1】:

    就像yedterior所说的,你可以通过实现一个write函数来定义一个自定义的io.Writer。您可能还想做一个 log.SetFlags(0) 来完全控制。这是一个更改日期格式并添加一些日志级别信息的示例。

    type logWriter struct {
    }
    
    func (writer logWriter) Write(bytes []byte) (int, error) {
        return fmt.Print(time.Now().UTC().Format("2006-01-02T15:04:05.999Z") + " [DEBUG] " + string(bytes))
    }
    
    func main() {
    
        log.SetFlags(0)
        log.SetOutput(new(logWriter))
        log.Println("This is something being logged!")
    }
    

    输出:

    2016-03-21T19:54:28.563Z [DEBUG] 这是正在记录的内容!

    【讨论】:

      【解决方案2】:

      使用 Logger 系统内部的标志要容易得多。

          log.SetFlags(log.Lmicroseconds)
      

      使用此标志将带有微秒的时间戳添加到日志中。 其他可用选项是:

      const (
      Ldate         = 1 << iota     // the date in the local time zone: 2009/01/23
      Ltime                         // the time in the local time zone: 01:23:23
      Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
      Llongfile                     // full file name and line number: /a/b/c/d.go:23
      Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
      LUTC                          // if Ldate or Ltime is set, use UTC rather than the local time zone
      Lmsgprefix                    // move the "prefix" from the beginning of the line to before the message
      LstdFlags     = Ldate | Ltime // initial values for the standard logger
      

      )

      Golang 记录器文档可用here

      【讨论】:

      • 确实更容易,但这并不能回答问题。 log.Lmicroseconds 与自定义日期格式无关。
      【解决方案3】:

      根据来源 (http://golang.org/src/pkg/log/log.go),没有内置方法可以做到这一点:

      26      // Bits or'ed together to control what's printed. There is no control over the
      27      // order they appear (the order listed here) or the format they present (as
      28      // described in the comments).  A colon appears after these items:
      29      //  2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
      

      您需要为此使用 3rd 方包,或按照 yed 所述截取日志输出。

      【讨论】:

        【解决方案4】:

        使用自定义编写器过滤日志行以将它们修改为您需要的格式。这应该很容易,因为标题的格式是常规且固定宽度的。然后调用 log.SetOutput(myFilterWriter(os.Stderr))。

        【讨论】:

          猜你喜欢
          • 2011-12-12
          • 2021-03-04
          • 2018-03-27
          • 1970-01-01
          • 2019-08-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-12-28
          相关资源
          最近更新 更多