From d63ca8b4eaee4be14557391739b52c631a4cfc9c Mon Sep 17 00:00:00 2001 From: Deen Date: Thu, 9 Jan 2020 12:21:43 +0800 Subject: [PATCH] Add millisecond duration encoder (#773) make ms encoder compatible for go version <=1.13.0 & add testcase for ms encoder --- zapcore/encoder.go | 8 ++++++++ zapcore/encoder_test.go | 1 + 2 files changed, 9 insertions(+) diff --git a/zapcore/encoder.go b/zapcore/encoder.go index 5e0a69be5..becc0ff88 100644 --- a/zapcore/encoder.go +++ b/zapcore/encoder.go @@ -168,6 +168,12 @@ func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendInt64(int64(d)) } +// MillisDurationEncoder serializes a time.Duration to an integer number of +// milliseconds elapsed. +func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { + enc.AppendInt64(d.Nanoseconds() / 1e6) +} + // StringDurationEncoder serializes a time.Duration using its built-in String // method. func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { @@ -183,6 +189,8 @@ func (e *DurationEncoder) UnmarshalText(text []byte) error { *e = StringDurationEncoder case "nanos": *e = NanosDurationEncoder + case "ms": + *e = MillisDurationEncoder default: *e = SecondsDurationEncoder } diff --git a/zapcore/encoder_test.go b/zapcore/encoder_test.go index 646b58a3f..3f521971a 100644 --- a/zapcore/encoder_test.go +++ b/zapcore/encoder_test.go @@ -566,6 +566,7 @@ func TestDurationEncoders(t *testing.T) { }{ {"string", "1.0000005s"}, {"nanos", int64(1000000500)}, + {"ms", int64(1000)}, {"", 1.0000005}, {"something-random", 1.0000005}, }