Go logger to print timestamp


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 ...



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] ")

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.

Answered By – Simon Whitehead

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.