From d10c2f9e3c9bf2debfd370a038ca8520f73bd405 Mon Sep 17 00:00:00 2001 From: David Bariod Date: Wed, 31 Oct 2018 07:01:35 +0100 Subject: [PATCH] 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 --- logrus_test.go | 12 ++++++++++++ text_formatter.go | 14 +++++++------- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/logrus_test.go b/logrus_test.go index f6a0f44..b12d71c 100644 --- a/logrus_test.go +++ b/logrus_test.go @@ -702,3 +702,15 @@ func TestLogLevelEnabled(t *testing.T) { assert.Equal(t, true, log.IsLevelEnabled(DebugLevel)) 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") +} diff --git a/text_formatter.go b/text_formatter.go index c5f9ca3..49ec92f 100644 --- a/text_formatter.go +++ b/text_formatter.go @@ -164,18 +164,18 @@ func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { } else { for _, key := range fixedKeys { var value interface{} - switch key { - case f.FieldMap.resolve(FieldKeyTime): + switch { + case key == f.FieldMap.resolve(FieldKeyTime): value = entry.Time.Format(timestampFormat) - case f.FieldMap.resolve(FieldKeyLevel): + case key == f.FieldMap.resolve(FieldKeyLevel): value = entry.Level.String() - case f.FieldMap.resolve(FieldKeyMsg): + case key == f.FieldMap.resolve(FieldKeyMsg): value = entry.Message - case f.FieldMap.resolve(FieldKeyLogrusError): + case key == f.FieldMap.resolve(FieldKeyLogrusError): value = entry.err - case f.FieldMap.resolve(FieldKeyFunc): + case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller(): 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) default: value = entry.Data[key]