From b2c6f8aa8b5298ac71ce8e3826c8cc417e6c7336 Mon Sep 17 00:00:00 2001 From: Ryan Canty Date: Thu, 17 Nov 2016 11:28:41 -0800 Subject: [PATCH] Added resolve method to clean up Format --- json_formatter.go | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/json_formatter.go b/json_formatter.go index 7364fe8..0c74e5a 100644 --- a/json_formatter.go +++ b/json_formatter.go @@ -5,6 +5,14 @@ import ( "fmt" ) +type fieldKey string + +const ( + DefaultKeyMsg = "msg" + DefaultKeyLevel = "level" + DefaultKeyTime = "time" +) + type JSONFormatter struct { // TimestampFormat sets the format used for marshaling timestamps. TimestampFormat string @@ -32,24 +40,9 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { timestampFormat = DefaultTimestampFormat } - timeKey := f.TimeKey - if timeKey == "" { - timeKey = "time" - } - - messageKey := f.MessageKey - if messageKey == "" { - messageKey = "msg" - } - - levelKey := f.LevelKey - if levelKey == "" { - levelKey = "level" - } - - data[timeKey] = entry.Time.Format(timestampFormat) - data[messageKey] = entry.Message - data[levelKey] = entry.Level.String() + data[f.resolveKey(f.TimeKey, DefaultKeyTime)] = entry.Time.Format(timestampFormat) + data[f.resolveKey(f.MessageKey, DefaultKeyMsg)] = entry.Message + data[f.resolveKey(f.LevelKey, DefaultKeyLevel)] = entry.Level.String() serialized, err := json.Marshal(data) if err != nil { @@ -57,3 +50,10 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { } return append(serialized, '\n'), nil } + +func (f *JSONFormatter) resolveKey(key, defaultKey string) string { + if len(key) > 0 { + return key + } + return defaultKey +}