From 1d329ad042a28dd4694bc10a1e6ce3b9a5e67a3c Mon Sep 17 00:00:00 2001 From: Andrew Burian Date: Mon, 21 Nov 2016 10:09:59 -0800 Subject: [PATCH] Added option to disable JSON timestamp Tests verify both the default and disabled case. --- json_formatter.go | 7 ++++++- json_formatter_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/json_formatter.go b/json_formatter.go index f3729bf..266554e 100644 --- a/json_formatter.go +++ b/json_formatter.go @@ -26,6 +26,9 @@ type JSONFormatter struct { // TimestampFormat sets the format used for marshaling timestamps. TimestampFormat string + // DisableTimestamp allows disabling automatic timestamps in output + DisableTimestamp bool + // FieldMap allows users to customize the names of keys for various fields. // As an example: // formatter := &JSONFormatter{ @@ -57,7 +60,9 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { timestampFormat = DefaultTimestampFormat } - data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) + if !f.DisableTimestamp { + data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) + } data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() diff --git a/json_formatter_test.go b/json_formatter_test.go index 5baa93e..2f9dae7 100644 --- a/json_formatter_test.go +++ b/json_formatter_test.go @@ -169,3 +169,31 @@ func TestJSONTimeKey(t *testing.T) { t.Fatal("Expected JSON to format time key") } } + +func TestJSONDisableTimestamp(t *testing.T) { + formatter := &JSONFormatter{ + DisableTimestamp: true, + } + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if strings.Contains(s, "time") { + t.Error("Did not prevent timestamp", s) + } +} + +func TestJSONEnableTimestamp(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("level", "something")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !strings.Contains(s, "time") { + t.Error("Timestamp not present", s) + } +}