From e0603bc6760ee48d32a4a96a0e9cc032698d8584 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Sat, 4 Feb 2023 11:30:18 -0800 Subject: [PATCH] log: fix and cleanup trailing newline logic The intent was to always append a newline if a newline was missing. The older logic accidentally only checked the payload for newlines and forgot to check the prefix as well. Fix it to check both together. This changes the output of Logger.Output in the situation where the prefix contains a trailing newline and the output is empty. This is a very rare combination and unlikely to occur in practice. Change-Id: Ic04ded6c29a90383e29bf7f59223a808ee1cbdc0 Reviewed-on: https://go-review.googlesource.com/c/go/+/465316 Reviewed-by: Brad Fitzpatrick TryBot-Result: Gopher Robot Reviewed-by: Ian Lance Taylor Reviewed-by: David Chase Run-TryBot: Ian Lance Taylor --- src/log/log.go | 4 +--- src/log/log_test.go | 9 +++++++++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/log/log.go b/src/log/log.go index 78458c19f3..c02a98be49 100644 --- a/src/log/log.go +++ b/src/log/log.go @@ -222,10 +222,8 @@ func (l *Logger) output(calldepth int, appendOutput func([]byte) []byte) error { buf := getBuffer() defer putBuffer(buf) formatHeader(buf, now, prefix, flag, file, line) - headerLen := len(*buf) *buf = appendOutput(*buf) - s := (*buf)[headerLen:] - if len(s) == 0 || s[len(s)-1] != '\n' { + if len(*buf) == 0 || (*buf)[len(*buf)-1] != '\n' { *buf = append(*buf, '\n') } diff --git a/src/log/log_test.go b/src/log/log_test.go index ea7e7917b8..b3b63d4e22 100644 --- a/src/log/log_test.go +++ b/src/log/log_test.go @@ -148,6 +148,15 @@ func TestFlagAndPrefixSetting(t *testing.T) { if !matched { t.Error("message did not match pattern") } + + // Ensure that a newline is added only if the buffer lacks a newline suffix. + b.Reset() + l.SetFlags(0) + l.SetPrefix("\n") + l.Output(0, "") + if got := b.String(); got != "\n" { + t.Errorf("message mismatch:\ngot %q\nwant %q", got, "\n") + } } func TestUTCFlag(t *testing.T) {