1
0
mirror of https://github.com/golang/go synced 2024-11-19 17:04:41 -07:00

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>
This commit is contained in:
Rob Pike 2015-04-08 14:55:45 -07:00
parent d64617fc0a
commit d340b10366
2 changed files with 17 additions and 2 deletions

View File

@ -156,7 +156,7 @@ func (l *Logger) Output(calldepth int, s string) error {
l.buf = l.buf[:0] l.buf = l.buf[:0]
l.formatHeader(&l.buf, now, file, line) l.formatHeader(&l.buf, now, file, line)
l.buf = append(l.buf, s...) l.buf = append(l.buf, s...)
if len(s) > 0 && s[len(s)-1] != '\n' { if len(s) == 0 || s[len(s)-1] != '\n' {
l.buf = append(l.buf, '\n') l.buf = append(l.buf, '\n')
} }
_, err := l.out.Write(l.buf) _, err := l.out.Write(l.buf)

View File

@ -10,6 +10,7 @@ import (
"bytes" "bytes"
"os" "os"
"regexp" "regexp"
"strings"
"testing" "testing"
) )
@ -17,7 +18,7 @@ const (
Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]` Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`
Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]` Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`
Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]` Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`
Rline = `(54|56):` // must update if the calls to l.Printf / l.Print below move Rline = `(55|57):` // must update if the calls to l.Printf / l.Print below move
Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline
Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline
) )
@ -118,6 +119,20 @@ func TestFlagAndPrefixSetting(t *testing.T) {
} }
} }
func TestEmptyPrintCreatesLine(t *testing.T) {
var b bytes.Buffer
l := New(&b, "Header:", LstdFlags)
l.Print()
l.Println("non-empty")
output := b.String()
if n := strings.Count(output, "Header"); n != 2 {
t.Errorf("expected 2 headers, got %d", n)
}
if n := strings.Count(output, "\n"); n != 2 {
t.Errorf("expected 2 lines, got %d", n)
}
}
func BenchmarkItoa(b *testing.B) { func BenchmarkItoa(b *testing.B) {
dst := make([]byte, 0, 64) dst := make([]byte, 0, 64)
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {