Skip to content

Commit

Permalink
Fix panic in log with empty header
Browse files Browse the repository at this point in the history
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".
  • Loading branch information
arp242 authored and aldas committed Jun 14, 2022
1 parent 64116ba commit 6267eb7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
6 changes: 4 additions & 2 deletions log/log.go
Expand Up @@ -391,7 +391,7 @@ func (l *Logger) log(level Lvl, format string, args ...interface{}) {
if err == nil {
s := buf.String()
i := buf.Len() - 1
if s[i] == '}' {
if i >= 0 && s[i] == '}' {
// JSON header
buf.Truncate(i)
buf.WriteByte(',')
Expand All @@ -404,7 +404,9 @@ func (l *Logger) log(level Lvl, format string, args ...interface{}) {
}
} else {
// Text header
buf.WriteByte(' ')
if len(s) > 0 {
buf.WriteByte(' ')
}
buf.WriteString(message)
}
buf.WriteByte('\n')
Expand Down
10 changes: 10 additions & 0 deletions log/log_test.go
Expand Up @@ -119,6 +119,16 @@ func TestStringWithQuotes(t *testing.T) {
assert.Contains(t, b.String(), `"message":"Content-Type: \"\""`)
}

func TestEmptyHeader(t *testing.T) {
l := New("test")
b := new(bytes.Buffer)
l.SetOutput(b)
l.SetHeader("")
l.SetLevel(DEBUG)
l.Debugf("captain's log")
assert.Contains(t, b.String(), `captain's log`)
}

func BenchmarkLog(b *testing.B) {
l := New("test")
l.SetOutput(new(bytes.Buffer))
Expand Down

0 comments on commit 6267eb7

Please sign in to comment.