From 5abe1567774fc54f6dbad085bb1ddaf19000e0dd Mon Sep 17 00:00:00 2001 From: Deluan Date: Sun, 18 Feb 2024 13:06:01 -0500 Subject: [PATCH] Logs don't panic when receiving a `nil` *time.Time --- log/log.go | 8 +++++++- log/log_test.go | 14 +++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/log/log.go b/log/log.go index c1d05845..3ffbb14b 100644 --- a/log/log.go +++ b/log/log.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "os" + "reflect" "runtime" "sort" "strings" @@ -267,7 +268,12 @@ func addFields(logger *logrus.Entry, keyValuePairs []interface{}) *logrus.Entry case time.Duration: logger = logger.WithField(name, ShortDur(v)) case fmt.Stringer: - logger = logger.WithField(name, v.String()) + vOf := reflect.ValueOf(v) + if vOf.Kind() == reflect.Pointer && vOf.IsNil() { + logger = logger.WithField(name, "nil") + } else { + logger = logger.WithField(name, v.String()) + } default: logger = logger.WithField(name, v) } diff --git a/log/log_test.go b/log/log_test.go index e54fa95f..0462988e 100644 --- a/log/log_test.go +++ b/log/log_test.go @@ -5,6 +5,7 @@ import ( "errors" "net/http/httptest" "testing" + "time" . "github.com/onsi/ginkgo/v2" . "github.com/onsi/gomega" @@ -91,9 +92,20 @@ var _ = Describe("Logger", func() { SetLogSourceLine(true) Error("A crash happened") // NOTE: This assertion breaks if the line number above changes - Expect(hook.LastEntry().Data[" source"]).To(ContainSubstring("/log/log_test.go:92")) + Expect(hook.LastEntry().Data[" source"]).To(ContainSubstring("/log/log_test.go:93")) Expect(hook.LastEntry().Message).To(Equal("A crash happened")) }) + + It("logs fmt.Stringer as a string", func() { + t := time.Now() + Error("Simple Message", "key1", t) + Expect(hook.LastEntry().Data["key1"]).To(Equal(t.String())) + }) + It("logs nil fmt.Stringer as nil", func() { + var t *time.Time + Error("Simple Message", "key1", t) + Expect(hook.LastEntry().Data["key1"]).To(Equal("nil")) + }) }) Describe("Levels", func() {