Skip to content

Commit

Permalink
fix slog handler to convert attributes of type err to string
Browse files Browse the repository at this point in the history
  • Loading branch information
ten4o authored and geofffranks committed Oct 4, 2024
1 parent 4ba9a85 commit 6330a49
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
6 changes: 5 additions & 1 deletion handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,11 @@ func processAttr(attr slog.Attr, target map[string]any) {
case attr.Key == "":
// skip
default:
target[attr.Key] = rv.Any()
if rvAsError, isError := rv.Any().(error); isError {
target[attr.Key] = rvAsError.Error()
} else {
target[attr.Key] = rv.Any()
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gstruct"
"fmt"
"log/slog"
"strconv"
"strings"
Expand Down Expand Up @@ -59,6 +60,20 @@ var _ = Describe("NewHandler", func() {
})))
})

It("logs an error message", func() {
slog.New(h).Error("foo", "error", fmt.Errorf("boom"))
logs := s.Logs()
Expect(logs).To(ConsistOf(MatchFields(IgnoreExtras, Fields{
"Source": Equal("test"),
"Message": Equal("test.foo"),
"Data": SatisfyAll(
HaveLen(1),
HaveKeyWithValue("error", "boom"),
),
"LogLevel": Equal(lager.ERROR),
})))
})

It("behaves like a slog.NewHandler", func() {
results := func() (result []map[string]any) {
for _, l := range s.Logs() {
Expand Down

0 comments on commit 6330a49

Please sign in to comment.