fix panic in text formatter

The panic was caused to a nil pointer access when report
caller was activated with output coloring disabled

Fixes #852
This commit is contained in:
David Bariod 2018-10-31 07:01:35 +01:00
parent 566a5f6908
commit d10c2f9e3c
2 changed files with 19 additions and 7 deletions

View File

@ -702,3 +702,15 @@ func TestLogLevelEnabled(t *testing.T) {
assert.Equal(t, true, log.IsLevelEnabled(DebugLevel)) assert.Equal(t, true, log.IsLevelEnabled(DebugLevel))
assert.Equal(t, true, log.IsLevelEnabled(TraceLevel)) assert.Equal(t, true, log.IsLevelEnabled(TraceLevel))
} }
func TestReportCallerOnTextFormatter(t *testing.T) {
l := New()
l.Formatter.(*TextFormatter).ForceColors = true
l.Formatter.(*TextFormatter).DisableColors = false
l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")
l.Formatter.(*TextFormatter).ForceColors = false
l.Formatter.(*TextFormatter).DisableColors = true
l.WithFields(Fields{"func": "func", "file": "file"}).Info("test")
}

View File

@ -164,18 +164,18 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
} else { } else {
for _, key := range fixedKeys { for _, key := range fixedKeys {
var value interface{} var value interface{}
switch key { switch {
case f.FieldMap.resolve(FieldKeyTime): case key == f.FieldMap.resolve(FieldKeyTime):
value = entry.Time.Format(timestampFormat) value = entry.Time.Format(timestampFormat)
case f.FieldMap.resolve(FieldKeyLevel): case key == f.FieldMap.resolve(FieldKeyLevel):
value = entry.Level.String() value = entry.Level.String()
case f.FieldMap.resolve(FieldKeyMsg): case key == f.FieldMap.resolve(FieldKeyMsg):
value = entry.Message value = entry.Message
case f.FieldMap.resolve(FieldKeyLogrusError): case key == f.FieldMap.resolve(FieldKeyLogrusError):
value = entry.err value = entry.err
case f.FieldMap.resolve(FieldKeyFunc): case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller():
value = entry.Caller.Function value = entry.Caller.Function
case f.FieldMap.resolve(FieldKeyFile): case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller():
value = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) value = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
default: default:
value = entry.Data[key] value = entry.Data[key]