Skip to content

Commit d340b10

Browse files
committed
log: logging an empty string should still print a line
Print("") was printing a header but no line. Fixes #9665. Change-Id: Iac783187786065e1389ad6e8d7ef02c579ed7bd8 Reviewed-on: https://go-review.googlesource.com/8665 Reviewed-by: Ian Lance Taylor <iant@golang.org>
1 parent d64617f commit d340b10

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

src/log/log.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ func (l *Logger) Output(calldepth int, s string) error {
156156
l.buf = l.buf[:0]
157157
l.formatHeader(&l.buf, now, file, line)
158158
l.buf = append(l.buf, s...)
159-
if len(s) > 0 && s[len(s)-1] != '\n' {
159+
if len(s) == 0 || s[len(s)-1] != '\n' {
160160
l.buf = append(l.buf, '\n')
161161
}
162162
_, err := l.out.Write(l.buf)

src/log/log_test.go

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@ import (
1010
"bytes"
1111
"os"
1212
"regexp"
13+
"strings"
1314
"testing"
1415
)
1516

1617
const (
1718
Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`
1819
Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`
1920
Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`
20-
Rline = `(54|56):` // must update if the calls to l.Printf / l.Print below move
21+
Rline = `(55|57):` // must update if the calls to l.Printf / l.Print below move
2122
Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline
2223
Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline
2324
)
@@ -118,6 +119,20 @@ func TestFlagAndPrefixSetting(t *testing.T) {
118119
}
119120
}
120121

122+
func TestEmptyPrintCreatesLine(t *testing.T) {
123+
var b bytes.Buffer
124+
l := New(&b, "Header:", LstdFlags)
125+
l.Print()
126+
l.Println("non-empty")
127+
output := b.String()
128+
if n := strings.Count(output, "Header"); n != 2 {
129+
t.Errorf("expected 2 headers, got %d", n)
130+
}
131+
if n := strings.Count(output, "\n"); n != 2 {
132+
t.Errorf("expected 2 lines, got %d", n)
133+
}
134+
}
135+
121136
func BenchmarkItoa(b *testing.B) {
122137
dst := make([]byte, 0, 64)
123138
for i := 0; i < b.N; i++ {

0 commit comments

Comments
 (0)