From 08e8d6501d300248a75c6375cfd3444b2469bb71 Mon Sep 17 00:00:00 2001 From: Maxim Sukharev Date: Wed, 5 Dec 2018 19:14:19 +0100 Subject: [PATCH] Skip func pointer type value in fields Before there was introduced a fix for JSONFormatter when func type value passed as Field. This commit does the same but for pointer to func. Ref: https://github.com/sirupsen/logrus/issues/642 https://github.com/sirupsen/logrus/pull/832 --- entry.go | 19 ++++++++++++++----- entry_test.go | 13 +++++++++++++ 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/entry.go b/entry.go index cc85d3a..4c00ba5 100644 --- a/entry.go +++ b/entry.go @@ -108,18 +108,27 @@ func (entry *Entry) WithFields(fields Fields) *Entry { for k, v := range entry.Data { data[k] = v } - var field_err string + var fieldErr string for k, v := range fields { - if t := reflect.TypeOf(v); t != nil && t.Kind() == reflect.Func { - field_err = fmt.Sprintf("can not add field %q", k) + isErrField := false + if t := reflect.TypeOf(v); t != nil { + switch t.Kind() { + case reflect.Func: + isErrField = true + case reflect.Ptr: + isErrField = t.Elem().Kind() == reflect.Func + } + } + if isErrField { + fieldErr = fmt.Sprintf("can not add field %q", k) if entry.err != "" { - field_err = entry.err + ", " + field_err + fieldErr = entry.err + ", " + fieldErr } } else { data[k] = v } } - return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: field_err} + return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr} } // Overrides the time of the Entry. diff --git a/entry_test.go b/entry_test.go index a81e2b3..7afcc11 100644 --- a/entry_test.go +++ b/entry_test.go @@ -113,3 +113,16 @@ func TestEntryHooksPanic(t *testing.T) { entry := NewEntry(logger) entry.Info(badMessage) } + +func TestEntryWithIncorrectField(t *testing.T) { + assert := assert.New(t) + + fn := func() {} + + e := Entry{} + eWithFunc := e.WithFields(Fields{"func": fn}) + eWithFuncPtr := e.WithFields(Fields{"funcPtr": &fn}) + + assert.Equal(eWithFunc.err, `can not add field "func"`) + assert.Equal(eWithFuncPtr.err, `can not add field "funcPtr"`) +}