From 368de753ea2a714981dac3bed7390460b9ae4a93 Mon Sep 17 00:00:00 2001 From: Aleksandr Kliuev Date: Wed, 10 Jul 2024 18:04:40 +0200 Subject: [PATCH] Preserve `tint.Err` attribute key (#66) * 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 --- handler.go | 6 +++--- handler_test.go | 8 ++++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/handler.go b/handler.go index 62d153c..d54b5d7 100644 --- a/handler.go +++ b/handler.go @@ -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) @@ -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) diff --git a/handler_test.go b/handler_test.go index 8e710fd..737f2d0 100644 --- a/handler_test.go +++ b/handler_test.go @@ -344,6 +344,14 @@ func TestHandler(t *testing.T) { }, Want: `Nov 10 23:00:00.000 INF test key="{A:123 B:}"`, }, + { // 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 {