Skip to content

Commit 12141b7

Browse files
dsneteric
authored andcommitted
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 <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]> Reviewed-by: David Chase <[email protected]> Run-TryBot: Ian Lance Taylor <[email protected]>
1 parent dd4312d commit 12141b7

File tree

2 files changed

+10
-3
lines changed

2 files changed

+10
-3
lines changed

src/log/log.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -222,10 +222,8 @@ func (l *Logger) output(calldepth int, appendOutput func([]byte) []byte) error {
222222
buf := getBuffer()
223223
defer putBuffer(buf)
224224
formatHeader(buf, now, prefix, flag, file, line)
225-
headerLen := len(*buf)
226225
*buf = appendOutput(*buf)
227-
s := (*buf)[headerLen:]
228-
if len(s) == 0 || s[len(s)-1] != '\n' {
226+
if len(*buf) == 0 || (*buf)[len(*buf)-1] != '\n' {
229227
*buf = append(*buf, '\n')
230228
}
231229

src/log/log_test.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,15 @@ func TestFlagAndPrefixSetting(t *testing.T) {
148148
if !matched {
149149
t.Error("message did not match pattern")
150150
}
151+
152+
// Ensure that a newline is added only if the buffer lacks a newline suffix.
153+
b.Reset()
154+
l.SetFlags(0)
155+
l.SetPrefix("\n")
156+
l.Output(0, "")
157+
if got := b.String(); got != "\n" {
158+
t.Errorf("message mismatch:\ngot %q\nwant %q", got, "\n")
159+
}
151160
}
152161

153162
func TestUTCFlag(t *testing.T) {

0 commit comments

Comments
 (0)