user2671513
user2671513

Reputation:

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

?

Upvotes: 4

Views: 19902

Answers (4)

hustljian
hustljian

Reputation: 1055

set go log flag log flags:

log.SetFlags(log.LstdFlags)

Upvotes: 4

sbueringer
sbueringer

Reputation: 31

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)

Upvotes: 3

Farshid T
Farshid T

Reputation: 2273

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.

Upvotes: 7

Simon Whitehead
Simon Whitehead

Reputation: 65049

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.

Upvotes: 6

Related Questions