mirror of https://github.com/sirupsen/logrus.git
Added customizable keys to JSON formatter
This commit is contained in:
parent
abc6f20dab
commit
2173899f8f
|
@ -8,6 +8,9 @@ import (
|
|||
type JSONFormatter struct {
|
||||
// TimestampFormat sets the format used for marshaling timestamps.
|
||||
TimestampFormat string
|
||||
MessageKey string
|
||||
LevelKey string
|
||||
TimeKey string
|
||||
}
|
||||
|
||||
func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
||||
|
@ -29,9 +32,24 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
|
|||
timestampFormat = DefaultTimestampFormat
|
||||
}
|
||||
|
||||
data["time"] = entry.Time.Format(timestampFormat)
|
||||
data["msg"] = entry.Message
|
||||
data["level"] = entry.Level.String()
|
||||
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()
|
||||
|
||||
serialized, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
|
|
|
@ -3,7 +3,7 @@ package logrus
|
|||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
@ -118,3 +118,42 @@ func TestJSONEntryEndsWithNewline(t *testing.T) {
|
|||
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")
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue