Added FieldMap to reduce potential struct bloat

This commit is contained in:
Ryan Canty 2016-11-17 15:16:46 -08:00
parent b2c6f8aa8b
commit d5ca23f998
No known key found for this signature in database
GPG Key ID: 2F7E8BA951840061
2 changed files with 31 additions and 20 deletions

View File

@ -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
}

View File

@ -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 {