Logs don't panic when receiving a `nil` *time.Time

This commit is contained in:
Deluan 2024-02-18 13:06:01 -05:00
parent fa72aaa462
commit 5abe156777
2 changed files with 20 additions and 2 deletions

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"os" "os"
"reflect"
"runtime" "runtime"
"sort" "sort"
"strings" "strings"
@ -267,7 +268,12 @@ func addFields(logger *logrus.Entry, keyValuePairs []interface{}) *logrus.Entry
case time.Duration: case time.Duration:
logger = logger.WithField(name, ShortDur(v)) logger = logger.WithField(name, ShortDur(v))
case fmt.Stringer: 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: default:
logger = logger.WithField(name, v) logger = logger.WithField(name, v)
} }

View File

@ -5,6 +5,7 @@ import (
"errors" "errors"
"net/http/httptest" "net/http/httptest"
"testing" "testing"
"time"
. "github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
@ -91,9 +92,20 @@ var _ = Describe("Logger", func() {
SetLogSourceLine(true) SetLogSourceLine(true)
Error("A crash happened") Error("A crash happened")
// NOTE: This assertion breaks if the line number above changes // 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")) 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() { Describe("Levels", func() {