diff --git a/json_formatter.go b/json_formatter.go index 0c74e5a..1e3e2bc 100644 --- a/json_formatter.go +++ b/json_formatter.go @@ -4,21 +4,27 @@ import ( "encoding/json" "fmt" ) - type fieldKey string +type FieldMap map[fieldKey]string const ( - DefaultKeyMsg = "msg" - DefaultKeyLevel = "level" - DefaultKeyTime = "time" + FieldKeyMsg = "msg" + FieldKeyLevel = "level" + FieldKeyTime = "time" ) +func (f FieldMap) resolve(key fieldKey) string { + if k, ok := f[key]; ok { + return k + } + + return string(key) +} + type JSONFormatter struct { // TimestampFormat sets the format used for marshaling timestamps. TimestampFormat string - MessageKey string - LevelKey string - TimeKey string + FieldMap FieldMap } func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { @@ -40,9 +46,9 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { timestampFormat = DefaultTimestampFormat } - 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() + data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) + data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message + data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() serialized, err := json.Marshal(data) if err != nil { @@ -50,10 +56,3 @@ 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 -} diff --git a/json_formatter_test.go b/json_formatter_test.go index 0fa3466..5baa93e 100644 --- a/json_formatter_test.go +++ b/json_formatter_test.go @@ -120,7 +120,11 @@ func TestJSONEntryEndsWithNewline(t *testing.T) { } func TestJSONMessageKey(t *testing.T) { - formatter := &JSONFormatter{MessageKey: "message"} + formatter := &JSONFormatter{ + FieldMap: FieldMap{ + FieldKeyMsg: "message", + }, + } b, err := formatter.Format(&Entry{Message: "oh hai"}) if err != nil { @@ -133,7 +137,11 @@ func TestJSONMessageKey(t *testing.T) { } func TestJSONLevelKey(t *testing.T) { - formatter := &JSONFormatter{LevelKey: "somelevel"} + formatter := &JSONFormatter{ + FieldMap: FieldMap{ + FieldKeyLevel: "somelevel", + }, + } b, err := formatter.Format(WithField("level", "something")) if err != nil { @@ -146,7 +154,11 @@ func TestJSONLevelKey(t *testing.T) { } func TestJSONTimeKey(t *testing.T) { - formatter := &JSONFormatter{TimeKey: "timeywimey"} + formatter := &JSONFormatter{ + FieldMap: FieldMap{ + FieldKeyTime: "timeywimey", + }, + } b, err := formatter.Format(WithField("level", "something")) if err != nil {