Skip to content

Commit e26d2d2

Browse files
committed
improve logger middleware error value logging
1 parent 65147fb commit e26d2d2

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

middleware/logger.go

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ package middleware
55

66
import (
77
"bytes"
8-
"encoding/json"
98
"io"
109
"strconv"
1110
"strings"
@@ -375,10 +374,7 @@ func LoggerWithConfig(config LoggerConfig) echo.MiddlewareFunc {
375374
return buf.WriteString(s)
376375
case "error":
377376
if err != nil {
378-
// Error may contain invalid JSON e.g. `"`
379-
b, _ := json.Marshal(err.Error())
380-
b = b[1 : len(b)-1]
381-
return buf.Write(b)
377+
return writeJSONSafeString(buf, err.Error())
382378
}
383379
case "latency":
384380
l := stop.Sub(start)

middleware/logger_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,21 @@ func TestLoggerDefaultMW(t *testing.T) {
4747
whenError: errors.New("error"),
4848
expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"error","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n",
4949
},
50+
{
51+
name: "error with invalid UTF-8 sequences",
52+
whenError: errors.New("invalid data: \xFF\xFE"),
53+
expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"invalid data: \ufffd\ufffd","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n",
54+
},
55+
{
56+
name: "error with JSON special characters (quotes and backslashes)",
57+
whenError: errors.New(`error with "quotes" and \backslash`),
58+
expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"error with \"quotes\" and \\backslash","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n",
59+
},
60+
{
61+
name: "error with control characters (newlines and tabs)",
62+
whenError: errors.New("error\nwith\nnewlines\tand\ttabs"),
63+
expect: `{"time":"2020-04-28T01:26:40Z","id":"","remote_ip":"192.0.2.1","host":"example.com","method":"GET","uri":"/","user_agent":"","status":500,"error":"error\nwith\nnewlines\tand\ttabs","latency":1,"latency_human":"1µs","bytes_in":0,"bytes_out":36}` + "\n",
64+
},
5065
{
5166
name: "ok, remote_ip from X-Real-Ip header",
5267
whenHeader: map[string]string{echo.HeaderXRealIP: "127.0.0.1"},

0 commit comments

Comments
 (0)