Add FieldMap support to TestFormatter

This commit is contained in:
Neil Isaac 2017-11-21 22:43:47 -05:00
parent 95cd2b9c79
commit bf1fb70b2b
2 changed files with 41 additions and 3 deletions

View File

@ -60,6 +60,15 @@ type TextFormatter struct {
// Whether the logger's out is to a terminal
isTerminal bool
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &JSONFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message"}}
FieldMap FieldMap
sync.Once
}
@ -109,11 +118,11 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
f.printColored(b, entry, keys, timestampFormat)
} else {
if !f.DisableTimestamp {
f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyTime), entry.Time.Format(timestampFormat))
}
f.appendKeyValue(b, "level", entry.Level.String())
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyLevel), entry.Level.String())
if entry.Message != "" {
f.appendKeyValue(b, "msg", entry.Message)
f.appendKeyValue(b, f.FieldMap.resolve(FieldKeyMsg), entry.Message)
}
for _, key := range keys {
f.appendKeyValue(b, key, entry.Data[key])

View File

@ -7,6 +7,8 @@ import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestFormatting(t *testing.T) {
@ -137,5 +139,32 @@ func TestDisableTimestampWithColoredOutput(t *testing.T) {
}
}
func TestTextFormatterFieldMap(t *testing.T) {
formatter := &TextFormatter{
DisableColors: true,
FieldMap: FieldMap{
FieldKeyMsg: "message",
FieldKeyLevel: "somelevel",
FieldKeyTime: "timeywimey",
},
}
entry := &Entry{
Message: "oh hi",
Level: WarnLevel,
Time: time.Date(1981, time.February, 24, 4, 28, 3, 100, time.UTC),
}
b, err := formatter.Format(entry)
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
assert.Equal(t,
`timeywimey="1981-02-24T04:28:03Z" somelevel=warning message="oh hi"`+"\n",
string(b),
"Formatted doesn't respect correct FieldMap")
}
// TODO add tests for sorting etc., this requires a parser for the text
// formatter output.