Added customizable keys to JSON formatter

This commit is contained in:
Ryan Canty 2016-08-15 11:04:25 -07:00
parent abc6f20dab
commit 2173899f8f
2 changed files with 61 additions and 4 deletions

View File

@ -8,6 +8,9 @@ import (
type JSONFormatter struct { type JSONFormatter struct {
// TimestampFormat sets the format used for marshaling timestamps. // TimestampFormat sets the format used for marshaling timestamps.
TimestampFormat string TimestampFormat string
MessageKey string
LevelKey string
TimeKey string
} }
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
@ -29,9 +32,24 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
timestampFormat = DefaultTimestampFormat timestampFormat = DefaultTimestampFormat
} }
data["time"] = entry.Time.Format(timestampFormat) timeKey := f.TimeKey
data["msg"] = entry.Message if timeKey == "" {
data["level"] = entry.Level.String() 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()
serialized, err := json.Marshal(data) serialized, err := json.Marshal(data)
if err != nil { if err != nil {

View File

@ -3,7 +3,7 @@ package logrus
import ( import (
"encoding/json" "encoding/json"
"errors" "errors"
"strings"
"testing" "testing"
) )
@ -118,3 +118,42 @@ func TestJSONEntryEndsWithNewline(t *testing.T) {
t.Fatal("Expected JSON log entry to end with a newline") t.Fatal("Expected JSON log entry to end with a newline")
} }
} }
func TestJSONMessageKey(t *testing.T) {
formatter := &JSONFormatter{MessageKey: "message"}
b, err := formatter.Format(&Entry{Message: "oh hai"})
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !(strings.Contains(s, "message") && strings.Contains(s, "oh hai")) {
t.Fatal("Expected JSON to format message key")
}
}
func TestJSONLevelKey(t *testing.T) {
formatter := &JSONFormatter{LevelKey: "somelevel"}
b, err := formatter.Format(WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, "somelevel") {
t.Fatal("Expected JSON to format level key")
}
}
func TestJSONTimeKey(t *testing.T) {
formatter := &JSONFormatter{TimeKey: "timeywimey"}
b, err := formatter.Format(WithField("level", "something"))
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, "timeywimey") {
t.Fatal("Expected JSON to format time key")
}
}