JSON Logger produces invalid JSON
robertkowalski opened this issue · comments
Robert Kowalski commented
When logging out JSON, newline delimiters like \n
and \r
are not properly escaped and produce invalid json
package main
import (
log "github.com/sirupsen/logrus"
)
func main() {
var mylog = log.New()
mylog.Formatter = &log.JSONFormatter{}
mylog.Errorf("hello foo\r\n bar\n")
}
$ go run test.go
{"level":"error","msg":"hello foo\r\n bar\n","time":"2022-04-04T12:53:33+02:00"}
$ node
Welcome to Node.js v16.14.2.
Type ".help" for more information.
> JSON.parse('{"level":"error","msg":"hello foo\r\n bar\n","time":"2022-04-04T12:53:33+02:00"}')
in JSON at position 33nexpected token
Expected result:
Special characters are properly escaped:
{"level":"error","msg":"hello foo\\r\\n bar\\n","time":"2022-04-04T12:53:33+02:00"}
Robert Kowalski commented
hm, wrote a test, it passes:
func TestJSONEscapeNewlines(t *testing.T) {
formatter := &JSONFormatter{}
b, err := formatter.Format(&Entry{Message: "foo\n \r\n"})
if err != nil {
t.Fatal("Unable to format entry: ", err)
}
s := string(b)
if !strings.Contains(s, "foo\\n \\r\\n") {
t.Error("Message should be escaped", s)
}
}
Robert Kowalski commented
seems they get lost during print?
Robert Kowalski commented
hm, maybe a shell issue:
$ echo "\\n"
\n
github-actions commented
This issue is stale because it has been open for 30 days with no activity.
github-actions commented
This issue was closed because it has been inactive for 14 days since being marked as stale.