From 7d977c65095d6fa7251e7b4d178aac1bc3a4a642 Mon Sep 17 00:00:00 2001 From: Jean Mertz Date: Sat, 9 Jun 2018 19:18:09 +0200 Subject: [PATCH] Use the correct format for the message timestamp As described in the Stackdriver documentation: > A timestamp in RFC3339 UTC "Zulu" format, accurate to nanoseconds. > Example: "2014-10-02T15:01:23.045123456Z". --- encoder.go | 14 ++++++++++++-- encoder_test.go | 13 +++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/encoder.go b/encoder.go index 10145f4..eec571f 100644 --- a/encoder.go +++ b/encoder.go @@ -1,6 +1,10 @@ package zapdriver -import "go.uber.org/zap/zapcore" +import ( + "time" + + "go.uber.org/zap/zapcore" +) // logLevelSeverity maps the Zap log levels to the correct level names as // defined by Stackdriver. @@ -37,7 +41,7 @@ var encoderConfig = zapcore.EncoderConfig{ StacktraceKey: "stacktrace", LineEnding: zapcore.DefaultLineEnding, EncodeLevel: EncodeLevel, - EncodeTime: zapcore.ISO8601TimeEncoder, + EncodeTime: RFC3339NanoTimeEncoder, EncodeDuration: zapcore.SecondsDurationEncoder, EncodeCaller: zapcore.ShortCallerEncoder, } @@ -47,3 +51,9 @@ var encoderConfig = zapcore.EncoderConfig{ func EncodeLevel(l zapcore.Level, enc zapcore.PrimitiveArrayEncoder) { enc.AppendString(logLevelSeverity[l]) } + +// RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339Nano-formatted +// string with nanoseconds precision. +func RFC3339NanoTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder) { + enc.AppendString(t.Format(time.RFC3339Nano)) +} diff --git a/encoder_test.go b/encoder_test.go index a28686a..dc9f87c 100644 --- a/encoder_test.go +++ b/encoder_test.go @@ -2,6 +2,7 @@ package zapdriver_test import ( "testing" + "time" "github.com/blendle/zapdriver" "github.com/stretchr/testify/assert" @@ -35,3 +36,15 @@ func TestEncodeLevel(t *testing.T) { }) } } + +func TestRFC3339NanoTimeEncoder(t *testing.T) { + t.Parallel() + + ts := time.Date(2018, 4, 9, 12, 43, 12, 678359, time.UTC) + + enc := &sliceArrayEncoder{} + zapdriver.RFC3339NanoTimeEncoder(ts, enc) + + require.Len(t, enc.elems, 1) + assert.Equal(t, ts.Format(time.RFC3339Nano), enc.elems[0].(string)) +}