Skip to content

Commit 6267eb7

Browse files
arp242aldas
authored andcommitted
Fix panic in log with empty header
Previously using `l.SetHeader("")` would panic with: --- FAIL: TestEmptyHeader (0.00s) panic: runtime error: index out of range [-1] [recovered] panic: runtime error: index out of range [-1] goroutine 18 [running]: github.com/labstack/gommon/log.(*Logger).log(0xc00014e990, 0x1, {0x5fb505, 0xd}, {0x0, 0x0, 0x0}) /home/martin/src/gommon/log/log.go:394 +0x615 github.com/labstack/gommon/log.(*Logger).Debugf(...) /home/martin/src/gommon/log/log.go:158 github.com/labstack/gommon/log.TestEmptyHeader(0xc000129860?) /home/martin/src/gommon/log/log_test.go:128 +0xb1 This adds a check for that. It also checks if there is any content before writing a space in the "Text header" else branch so you don't end up with " my message".
1 parent 64116ba commit 6267eb7

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

log/log.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ func (l *Logger) log(level Lvl, format string, args ...interface{}) {
391391
if err == nil {
392392
s := buf.String()
393393
i := buf.Len() - 1
394-
if s[i] == '}' {
394+
if i >= 0 && s[i] == '}' {
395395
// JSON header
396396
buf.Truncate(i)
397397
buf.WriteByte(',')
@@ -404,7 +404,9 @@ func (l *Logger) log(level Lvl, format string, args ...interface{}) {
404404
}
405405
} else {
406406
// Text header
407-
buf.WriteByte(' ')
407+
if len(s) > 0 {
408+
buf.WriteByte(' ')
409+
}
408410
buf.WriteString(message)
409411
}
410412
buf.WriteByte('\n')

log/log_test.go

+10
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,16 @@ func TestStringWithQuotes(t *testing.T) {
119119
assert.Contains(t, b.String(), `"message":"Content-Type: \"\""`)
120120
}
121121

122+
func TestEmptyHeader(t *testing.T) {
123+
l := New("test")
124+
b := new(bytes.Buffer)
125+
l.SetOutput(b)
126+
l.SetHeader("")
127+
l.SetLevel(DEBUG)
128+
l.Debugf("captain's log")
129+
assert.Contains(t, b.String(), `captain's log`)
130+
}
131+
122132
func BenchmarkLog(b *testing.B) {
123133
l := New("test")
124134
l.SetOutput(new(bytes.Buffer))

0 commit comments

Comments
 (0)