Skip to content

Commit

Permalink
fix: slog adapter panics when .Err() recieves nil (#11)
Browse files Browse the repository at this point in the history
Signed-off-by: Alex Sørlie <alex@sorlie.io>
  • Loading branch information
SuperManifolds authored Jan 31, 2025
1 parent b1c518d commit 56b17a3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions loggers/slog/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,9 @@ func (c *Context) MACAddr(key string, macAddr net.HardwareAddr) types.Context {
}

func (c *Context) Err(err error) types.Context {
if err == nil {
return c
}
c.attrs = append(c.attrs, slog.Attr{
Key: "error",
Value: slog.StringValue(err.Error()),
Expand Down
3 changes: 3 additions & 0 deletions loggers/slog/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ func (e *Event) MACAddr(key string, macAddr net.HardwareAddr) types.Event {
}

func (e *Event) Err(err error) types.Event {
if err == nil {
return e
}
e.attr = append(e.attr, slog.Attr{
Key: types.ErrorKey,
Value: slog.StringValue(err.Error()),
Expand Down
23 changes: 23 additions & 0 deletions logging_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,29 @@ func TestInfo(t *testing.T) {
})
})

t.Run("nil", func(t *testing.T) {
t.Run("noop", func(t *testing.T) {
out := &bytes.Buffer{}
log := New(Noop, t.Name(), out)
log.Error().Err(nil).Msg("test")
assert.Equal(t, "", out.String())
})

t.Run("zerolog", func(t *testing.T) {
out := &bytes.Buffer{}
log := New(Zerolog, t.Name(), out)
log.Error().Err(nil).Msg("test")
assert.Equal(t, fillZerologTestFields(t, "{\"level\":\"error\",\"time\":\"%s\",\"source\":\"%s\",\"message\":\"test\"}\n"), out.String())
})

t.Run("slog", func(t *testing.T) {
out := &bytes.Buffer{}
log := New(Slog, t.Name(), out)
log.Error().Err(nil).Msg("test")
assert.Equal(t, fillSlogTestFields(t, "level=ERROR msg=test source=%s\n"), out.String())
})
})

t.Run("one-field", func(t *testing.T) {
t.Run("noop", func(t *testing.T) {
out := &bytes.Buffer{}
Expand Down

0 comments on commit 56b17a3

Please sign in to comment.