4

Go logger to print timestamp

I have the following:

l := log.New(os.Stdout, "[AAA] ", 2)
l.Printf("Listening on %s", addr)

This prints out [AAA] Listening on ~

Is there any way that I can configure log package to print out

2014-09-15 10:23:12 [AAA] Listening on ...

?

1
  • You should consider using glog, a pretty full featured log pkg.
    – jmaloney
    Oct 2, 2014 at 1:37

4 Answers 4

7
l := log.New(os.Stdout, "[AAA] ", 2)
l.Printf("Listening on %s", addr)

Prints out [AAA] 17:07:51 Listening on ...

If you want to add the date, use log.Ldate | log.Ltime as flag:

l := log.New(os.Stdout, "[AAA] ", log.Ldate | log.Ltime)
l.Printf("Listening on %s", addr)
// [AAA] 2016-07-14 17:07:51 Listening on ...

But for having the date and time before prefix, you can use a customized writer:

type writer struct {
    io.Writer
    timeFormat string
}

func (w writer) Write(b []byte) (n int, err error) {
    return w.Writer.Write(append([]byte(time.Now().Format(w.timeFormat)), b...))
}

Then, pass the custom writer to log's New:

l := log.New(&writer{os.Stdout, "2006-01-02 15:04:05 "}, "[AAA] ", 0)

l.Printf("Listening on %s", addr)
// 2016-07-14 17:07:51 [AAA] Listening on ...

There is a complete example here.

6

To get your specific requested output, you can wrap it in your own Log function and set the prefix each time using SetPrefix (or embed a logger in your own type and extend it with another function):

func Log(l *log.Logger, msg string) {
    l.SetPrefix(time.Now().Format("2006-01-02 15:04:05") + " [AAA] ")
    l.Print(msg)
}

For example:

l := log.New(os.Stdout, "", 0)

Log(l, "Log 1")

<-time.After(time.Second * 3)

Log(l, "Log 2")

..outputs this on my machine:

2014-10-02 11:12:14 [AAA] Log 1
2014-10-02 11:12:17 [AAA] Log 2

Note that the log package has some predefined flags that you can use, however they don't produce the format you've requested in your question. To get it exactly like that, you have to pass zero for the flags and do it yourself.

4
  • 1
    This Log function will acquire and release the loggers mutex twice. It might be more efficient to simply print the desired prefix.
    – Volker
    Oct 2, 2014 at 7:30
  • So it does! I was unaware that it acquired a lock for setting the prefix. Thanks @Volker Oct 2, 2014 at 9:03
  • For high-throughput, low-latency logging, this solution doesn't seem very performant. Have a look at this example here play.golang.org/p/Sup-mCZe9k and run it on your local box. On my MacBook I observe a 1 to 3 millisecond lag in log writes on average, which for many applications is unacceptable. The SetPrefix() method appears very expensive.
    – nmurthy
    Aug 10, 2017 at 20:13
  • 1
    @nmurthy Sure, Volker mentions its quite slow in the comments above yours. This does directly answer the OPs question though.. so I'm not sure why you've decided to downvote. The OP doesn't explicitly state high perf logging is a requirement and has accepted the answer. I'm not sure downvoting is required if the answer doesn't help you ... its more whether it helps the OP in the context of their original question, which it has... given its accepted. Aug 10, 2017 at 22:51
4

set go log flag log flags:

log.SetFlags(log.LstdFlags)
2
  • adds a date, but after the prefix, not before.
    – erik258
    Nov 14, 2019 at 21:43
  • Its log.SetFlags(log.LstdFlags) or log.SetFlags(3) And log.Print("Hello world") as 2022/02/02 19:36:00 Hello world Feb 2, 2022 at 14:09
3

Not sure when it was added but you can also just set the Lmsgprefix flag

Lmsgprefix   // move the "prefix" from the beginning of the line to before the message

e.g.:

log.SetFlags(log.Lmsgprefix | log.LstdFlags)
1
  • This is the most accurate answer. ` func logger(whichController string) *log.Logger { return log.New(os.Stderr, whichController, log.Lmsgprefix|log.LstdFlags) } headerReq := r.Header.Get("X-Request-ID") log := logger(fmt.Sprintf("[post: /logins req id %s] ", headerReq)) ` will produce messages like 2023/07/22 19:05:11 [post: /logins req id 123] loginUseCase.Execute - starting login use case
    – Virmundi
    Jul 22 at 23:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.