From 156a4e8b0fd1195b0fa02a7f3172d3b36974daab Mon Sep 17 00:00:00 2001 From: Olivier Poitrey Date: Fri, 19 May 2017 22:14:51 -0700 Subject: [PATCH] Use TimeFieldFormat for Timestamp field --- field.go | 5 ++++- globals.go | 2 ++ log_test.go | 4 ++-- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/field.go b/field.go index 97d08ab..a4706d6 100644 --- a/field.go +++ b/field.go @@ -78,11 +78,14 @@ func appendFloat64(dst []byte, key string, val float64) []byte { } func appendTime(dst []byte, key string, t time.Time) []byte { + if TimeFieldFormat == "" { + return appendInt64(dst, key, t.Unix()) + } return append(t.AppendFormat(append(appendKey(dst, key), '"'), TimeFieldFormat), '"') } func appendTimestamp(dst []byte) []byte { - return appendInt64(dst, TimestampFieldName, now().Unix()) + return appendTime(dst, TimestampFieldName, now()) } func appendObject(dst []byte, key string, obj interface{}) []byte { diff --git a/globals.go b/globals.go index d600ea5..77c68b9 100644 --- a/globals.go +++ b/globals.go @@ -20,6 +20,8 @@ var ( SampleFieldName = "sample" // TimeFieldFormat defines the time format of the Time field type. + // If set to an empty string, the time is formatted as an UNIX timestamp + // as integer. TimeFieldFormat = time.RFC3339 ) diff --git a/log_test.go b/log_test.go index 4409b35..0edc0ea 100644 --- a/log_test.go +++ b/log_test.go @@ -247,7 +247,7 @@ func TestContextTimestamp(t *testing.T) { log := New(out).With().Timestamp().Str("foo", "bar").Logger() log.Log().Msg("hello world") - if got, want := out.String(), `{"time":981173106,"foo":"bar","message":"hello world"}`+"\n"; got != want { + if got, want := out.String(), `{"time":"2001-02-03T04:05:06Z","foo":"bar","message":"hello world"}`+"\n"; got != want { t.Errorf("invalid log output: got %q, want %q", got, want) } } @@ -263,7 +263,7 @@ func TestEventTimestamp(t *testing.T) { log := New(out).With().Str("foo", "bar").Logger() log.Log().Timestamp().Msg("hello world") - if got, want := out.String(), `{"foo":"bar","time":981173106,"message":"hello world"}`+"\n"; got != want { + if got, want := out.String(), `{"foo":"bar","time":"2001-02-03T04:05:06Z","message":"hello world"}`+"\n"; got != want { t.Errorf("invalid log output: got %q, want %q", got, want) } }