1
0
mirror of https://github.com/golang/go synced 2024-09-28 23:14:38 -06:00

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 <bradfitz@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@google.com>
Reviewed-by: David Chase <drchase@google.com>
Run-TryBot: Ian Lance Taylor <iant@google.com>
This commit is contained in:
Joe Tsai 2023-02-04 11:30:18 -08:00 committed by Joseph Tsai
parent 677038f866
commit e0603bc676
2 changed files with 10 additions and 3 deletions

View File

@ -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')
}

View File

@ -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) {