From 35dfd2b81a289d98cc20c93a884d92132302758f Mon Sep 17 00:00:00 2001 From: Igor Sechyn Date: Thu, 13 Apr 2017 14:26:40 +1000 Subject: [PATCH] core: add DisableHTMLEscape flag to json_formatter --- json_formatter.go | 17 +++++++++++++++-- json_formatter_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/json_formatter.go b/json_formatter.go index 266554e9f..45f0f70ad 100644 --- a/json_formatter.go +++ b/json_formatter.go @@ -1,6 +1,7 @@ package logrus import ( + "bytes" "encoding/json" "fmt" ) @@ -29,6 +30,9 @@ type JSONFormatter struct { // DisableTimestamp allows disabling automatic timestamps in output DisableTimestamp bool + // DisableHTMLEscape allows disabling html escaping in output + DisableHTMLEscape bool + // FieldMap allows users to customize the names of keys for various fields. // As an example: // formatter := &JSONFormatter{ @@ -66,9 +70,18 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() - serialized, err := json.Marshal(data) + serialized, err := f.serialize(data) if err != nil { return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) } - return append(serialized, '\n'), nil + return serialized, nil +} + +func (f *JSONFormatter) serialize(data Fields) ([]byte, error) { + buf := new(bytes.Buffer) + enc := json.NewEncoder(buf) + enc.SetEscapeHTML(!f.DisableHTMLEscape) + err := enc.Encode(data) + + return buf.Bytes(), err } diff --git a/json_formatter_test.go b/json_formatter_test.go index 51093a79b..64d6c392b 100644 --- a/json_formatter_test.go +++ b/json_formatter_test.go @@ -197,3 +197,29 @@ func TestJSONEnableTimestamp(t *testing.T) { t.Error("Timestamp not present", s) } } + +func TestJSONDisableHTMLEscape(t *testing.T) { + formatter := &JSONFormatter{DisableHTMLEscape: true} + + b, err := formatter.Format(&Entry{Message: "& < >"}) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !strings.Contains(s, "& < >") { + t.Error("Message should not be HTML escaped", s) + } +} + +func TestJSONEnableHTMLEscape(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(&Entry{Message: "& < >"}) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !(strings.Contains(s, "u0026") && strings.Contains(s, "u003e") && strings.Contains(s, "u003c")) { + t.Error("Message should be HTML escaped", s) + } +}