From 50ad8423415995ae716c97d1abf9b2472eb1c4f9 Mon Sep 17 00:00:00 2001 From: Jonathan Rockway <2367+jrockway@users.noreply.github.com> Date: Thu, 16 Jun 2022 05:48:12 -0400 Subject: [PATCH] Avoid letting logs with '\r's corrupt the output MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit \n doesn't really mess up the output, but it made sense to do the same thing for fields that we do for the message itself. This does make things like stacktrace keys harder to read, so we might want to make this configurable. Fixes #2. Before: ``` $ (for i in `seq 1 3`; do echo '{"ts":1,"level":"info","msg":"foo\r\n","key":"foo\n","another":"foo\rbar"}'; done) | jlog ↩ key:foo 31 19:00:01 foo barother:foo ↩ key:↑ another:↑0:01 foo ↩ key:↑ another:↑0:01 foo 3 lines read; no parse errors. ``` After: ``` $ (for i in `seq 1 3`; do echo '{"ts":1,"level":"info","msg":"foo\r\n","key":"foo\n","another":"foo\rbar"}'; done) | go run ./cmd/jlog INFO Dec 31 19:00:01 foo←↩ key:foo↩ another:foo←bar INFO Dec 31 19:00:01 foo←↩ key:↑ another:↑ INFO Dec 31 19:00:01 foo←↩ key:↑ another:↑ 3 lines read; no parse errors. ``` --- pkg/parse/default_formats.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/pkg/parse/default_formats.go b/pkg/parse/default_formats.go index 89ec23b..2cae7e9 100644 --- a/pkg/parse/default_formats.go +++ b/pkg/parse/default_formats.go @@ -88,8 +88,14 @@ func (f *DefaultOutputFormatter) FormatTime(s *State, t time.Time, w *bytes.Buff s.lastTime = t } +func cleanupNewlines(msg string) string { + msg = strings.ReplaceAll(msg, "\n", "↩") + msg = strings.ReplaceAll(msg, "\r", "←") + return msg +} + func (f *DefaultOutputFormatter) FormatMessage(s *State, msg string, highlight bool, w *bytes.Buffer) { - msg = strings.Replace(msg, "\n", "↩", -1) + msg = cleanupNewlines(msg) if highlight { msg = f.Aurora.Inverse(msg).String() } @@ -137,6 +143,7 @@ func (f *DefaultOutputFormatter) FormatField(s *State, k string, v interface{}, var value []byte switch x := v.(type) { case string: + x = cleanupNewlines(x) value = []byte(x) default: var err error