From c064b5c44b285a7e2fd5c9b26e8c38228ce2bccb Mon Sep 17 00:00:00 2001 From: Erno Hopearuoho Date: Tue, 7 Feb 2017 06:17:37 +0200 Subject: [PATCH] Add RFC3339NanoFormatter and UnixNanoFormatter (#276) --- json_options.go | 16 ++++++++++++++++ json_options_test.go | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/json_options.go b/json_options.go index 0e1ce8ccc..812f766b0 100644 --- a/json_options.go +++ b/json_options.go @@ -59,6 +59,14 @@ func EpochFormatter(key string) TimeFormatter { }) } +// UnixNanoFormatter encodes the entry time as a single int64 with nanosecond +// precision under the provided key. +func UnixNanoFormatter(key string) TimeFormatter { + return TimeFormatter(func(t time.Time) Field { + return Int64(key, t.UnixNano()) + }) +} + // RFC3339Formatter encodes the entry time as an RFC3339-formatted string under // the provided key. func RFC3339Formatter(key string) TimeFormatter { @@ -67,6 +75,14 @@ func RFC3339Formatter(key string) TimeFormatter { }) } +// RFC3339NanoFormatter encodes the entry time as an RFC3339-formatted string +// with nanosecond precision under the provided key. +func RFC3339NanoFormatter(key string) TimeFormatter { + return TimeFormatter(func(t time.Time) Field { + return String(key, t.Format(time.RFC3339Nano)) + }) +} + // NoTime drops the entry time altogether. It's often useful in testing, since // it removes the need to stub time.Now. func NoTime() TimeFormatter { diff --git a/json_options_test.go b/json_options_test.go index 80d568712..0dc964e85 100644 --- a/json_options_test.go +++ b/json_options_test.go @@ -22,6 +22,7 @@ package zap import ( "testing" + "time" "github.com/stretchr/testify/assert" ) @@ -60,6 +61,23 @@ func TestTimeFormatters(t *testing.T) { } } +func TestNanoTimeFormatters(t *testing.T) { + testtime := time.Date(2017, time.February, 4, 18, 48, 2, 300537459, time.UTC) + + tests := []struct { + name string + formatter TimeFormatter + expected Field + }{ + {"UnixNanoFormatter", UnixNanoFormatter("the-time"), Int64("the-time", 1486234082300537459)}, + {"RFC3339Nano", RFC3339NanoFormatter("ts"), String("ts", "2017-02-04T18:48:02.300537459Z")}, + } + + for _, tt := range tests { + assert.Equal(t, tt.expected, tt.formatter(testtime), "Unexpected output from TimeFormatter %s.", tt.name) + } +} + func TestLevelFormatters(t *testing.T) { const lvl = InfoLevel tests := []struct {