]> Cypherpunks repositories - gostls13.git/commitdiff
log: fix and cleanup trailing newline logic
authorJoe Tsai <joetsai@digital-static.net>
Sat, 4 Feb 2023 19:30:18 +0000 (11:30 -0800)
committerJoseph Tsai <joetsai@digital-static.net>
Mon, 6 Feb 2023 18:44:49 +0000 (18:44 +0000)
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>

src/log/log.go
src/log/log_test.go

index 78458c19f394d26c7467d7c0d77f7e7c774883a7..c02a98be4908b8c3dc217ef629d8d163c2080242 100644 (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')
        }
 
index ea7e7917b8380a0338bd7cd8edcfd2b90213e205..b3b63d4e223db57f29ad09a670835d2b7682d4ea 100644 (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) {