From d029c30efdb0658cbd659f32d36eb8dda7c03ed8 Mon Sep 17 00:00:00 2001 From: Takada Date: Tue, 25 Jun 2019 02:10:46 +0900 Subject: [PATCH] Add DisableEscapeHTML parameter to JSONFormatter --- json_formatter.go | 6 ++++++ json_formatter_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/json_formatter.go b/json_formatter.go index 098a21a06..66af0088b 100644 --- a/json_formatter.go +++ b/json_formatter.go @@ -51,6 +51,9 @@ type JSONFormatter struct { // PrettyPrint will indent all json logs PrettyPrint bool + + // DisableEscapeHTML allows disabling HTML escape. + DisableEscapeHTML bool } // Format renders a single log entry @@ -110,6 +113,9 @@ func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { } encoder := json.NewEncoder(b) + if f.DisableEscapeHTML { + encoder.SetEscapeHTML(false) + } if f.PrettyPrint { encoder.SetIndent("", " ") } diff --git a/json_formatter_test.go b/json_formatter_test.go index 695c36e54..b72d0c889 100644 --- a/json_formatter_test.go +++ b/json_formatter_test.go @@ -344,3 +344,32 @@ func TestJSONEnableTimestamp(t *testing.T) { t.Error("Timestamp not present", s) } } + +func TestJSONDisableEscapeHTML(t *testing.T) { + formatter := &JSONFormatter{ + DisableEscapeHTML: true, + } + + b, err := formatter.Format(WithField("xml", "&")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + if !strings.Contains(s, "&") { + t.Error("Raw keyword does not find", s) + } +} + +func TestJSONEnableEscapeHTML(t *testing.T) { + formatter := &JSONFormatter{} + + b, err := formatter.Format(WithField("xml", "&")) + if err != nil { + t.Fatal("Unable to format entry: ", err) + } + s := string(b) + escaped := `\u003cxml\u003e\u0026\u003c/xml\u003e` // same `&` + if !strings.Contains(s, escaped) { + t.Error("Escaped keyword does not find", s) + } +}