zerolog icon indicating copy to clipboard operation
zerolog copied to clipboard

Can't output millsecond correctly

Open wsyqn6 opened this issue 4 years ago • 4 comments

I have setted TimeFormat with millsecond,but the output does not display ms part.however use the same format at time.Format display is correct. I thought in some cases display with millsecond part is very useful!Maybe you can consider about it. Sincere thanks!

log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr, TimeFormat: "2006-01-02 15:04:05.000"})
log.Print(time.Now().Format("2006-01-02 15:04:05.000"))

actually output

2021-07-21 10:54:56.000 DBG 2021-07-21 10:54:56.261

wsyqn6 avatar Jul 21 '21 03:07 wsyqn6

@rs - I would like to take this up

rohithv1997 avatar Dec 04 '21 15:12 rohithv1997

@rs @a641390597 - seems like a bug in time.Parse()

Please refer the below code and its output for reference:

package main

import (
	"fmt"
	"time"
)

func main() {
	format := "2006-01-02 15:04:05.000"
	d1 := time.Now().Format(time.RFC3339)
	fmt.Println(d1)
	d2, err := time.Parse(time.RFC3339, d1)
	fmt.Println(d2)
	fmt.Println(err)
	d3 := d2.Format(format)
	fmt.Println(d3)
	d4 := time.Now()
	fmt.Println(d4)
	d5 := d4.Format(format)
	fmt.Println(d5)
}

Output:

2021-12-05T11:58:01+05:30
2021-12-05 11:58:01 +0530 IST
<nil>
2021-12-05 11:58:01.000
2021-12-05 11:58:01.54980146 +0530 IST m=+0.000124406
2021-12-05 11:58:01.549

rohithv1997 avatar Dec 05 '21 06:12 rohithv1997

zerolog.TimeFieldFormat = time.RFC3339Nano
// zerolog.TimeFieldFormat = "2006-01-02 15:04:05.000"

molon avatar Dec 07 '21 14:12 molon

Solution and explanation

By default, zerolog uses a time calculation precision of seconds. This is for performance reasons, I think.

As stated in the documentation (README), just do

zerolog.TimeFieldFormat = zerolog.TimeFormatUnixMicro

then you can specify a timestamp format up to the microsecond.

StephanHCB avatar Mar 26 '22 18:03 StephanHCB

[Edited, since my original post was misleading.]

Note to those who override aspects of ConsoleWriter: if you want extra precision in console formats, you must also set zerolog.TimeFieldFormat to have extra precision, as noted above.

In earlier versions, the timestamp added to the log prior to formatting was the time number, which wasn't very readable in JSON format. At some point this changed to string, making the JSON more readable, but also making it so that those who override fields in ConsoleWriter need to also set zerolog.TimeFieldFormat.

jlearman avatar Aug 31 '23 14:08 jlearman

IMHO this issue could be closed. I had the same issue as the OP, and the solution posted above works.

jlearman avatar Aug 31 '23 14:08 jlearman