Skip to content

Commit

Permalink
Preserve tint.Err attribute key (#66)
Browse files Browse the repository at this point in the history
* Preserve the 'err' Attribute Name

We do not always have control over how attribute names are defined.
However, it is beneficial to highlight errors in development logs for better visibility.

* make testcase consistent with the test suite

---------

Co-authored-by: lmittmann <[email protected]>
  • Loading branch information
kwargs and lmittmann authored Jul 10, 2024
1 parent 069f95f commit 368de75
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
6 changes: 3 additions & 3 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ func (h *handler) appendAttr(buf *buffer, attr slog.Attr, groupsPrefix string, g
}
} else if err, ok := attr.Value.Any().(tintError); ok {
// append tintError
h.appendTintError(buf, err, groupsPrefix)
h.appendTintError(buf, err, attr.Key, groupsPrefix)
buf.WriteByte(' ')
} else {
h.appendKey(buf, attr.Key, groupsPrefix)
Expand Down Expand Up @@ -395,9 +395,9 @@ func (h *handler) appendValue(buf *buffer, v slog.Value, quote bool) {
}
}

func (h *handler) appendTintError(buf *buffer, err error, groupsPrefix string) {
func (h *handler) appendTintError(buf *buffer, err error, attrKey, groupsPrefix string) {
buf.WriteStringIf(!h.noColor, ansiBrightRedFaint)
appendString(buf, groupsPrefix+errKey, true)
appendString(buf, groupsPrefix+attrKey, true)
buf.WriteByte('=')
buf.WriteStringIf(!h.noColor, ansiResetFaint)
appendString(buf, err.Error(), true)
Expand Down
8 changes: 8 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,14 @@ func TestHandler(t *testing.T) {
},
Want: `Nov 10 23:00:00.000 INF test key="{A:123 B:<nil>}"`,
},
{ // https://github.com/lmittmann/tint/pull/66
F: func(l *slog.Logger) {
errAttr := tint.Err(errors.New("fail"))
errAttr.Key = "error"
l.Error("test", errAttr)
},
Want: `Nov 10 23:00:00.000 ERR test error=fail`,
},
}

for i, test := range tests {
Expand Down

0 comments on commit 368de75

Please sign in to comment.