Skip to content

Commit

Permalink
fix: inline Attrs for a group with an empty key (#27)
Browse files Browse the repository at this point in the history
* fix: inline Attrs for a group with an empty key

This fixes a bug where tint produces `.c=d` if the user passes an
attribute like `slog.Group("", slog.String("c", "d"))`. This result
violates one of slog's rules for handlers: "If a group's key is empty,
inline the group's Attrs."

* added test case comment

* consistency

---------

Co-authored-by: lmittmann <[email protected]>
  • Loading branch information
telemachus and lmittmann committed Aug 14, 2023
1 parent 42cbc13 commit d74d683
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
4 changes: 3 additions & 1 deletion handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,9 @@ func (h *handler) appendAttr(buf *buffer, attr slog.Attr, groupsPrefix string) {

switch attr.Value.Kind() {
case slog.KindGroup:
groupsPrefix += attr.Key + "."
if attr.Key != "" {
groupsPrefix += attr.Key + "."
}
for _, groupAttr := range attr.Value.Group() {
h.appendAttr(buf, groupAttr, groupsPrefix)
}
Expand Down
6 changes: 6 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,12 @@ func TestHandler(t *testing.T) {
},
Want: `Nov 11 23:00:00.000 ERR test`,
},
{ // https://github.com/lmittmann/tint/pull/27
F: func(l *slog.Logger) {
l.Info("test", "a", "b", slog.Group("", slog.String("c", "d")), "e", "f")
},
Want: `Nov 10 23:00:00.000 INF test a=b c=d e=f`,
},
}

for i, test := range tests {
Expand Down

0 comments on commit d74d683

Please sign in to comment.