From bb2bad1ea8a38b4d738df5ec1843bb2ff622562e Mon Sep 17 00:00:00 2001 From: Victor Alves Date: Thu, 26 Sep 2019 14:41:18 +0200 Subject: [PATCH] add AttachError() to log package AttachError() method add a new context to Logger with key `attached_error` as the keyword to contribute with the best practices when using the log package. HH-111 --- log/logctx.go | 6 ++++++ log/logctx_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/log/logctx.go b/log/logctx.go index ecf60f7..8aec2b5 100644 --- a/log/logctx.go +++ b/log/logctx.go @@ -35,3 +35,9 @@ func Add(l Logger, cc ...Contexter) Logger { } return l } + +// AttachError adds a context called `attached_error` for error message that +// is relevant to the log entry. +func AttachError(l Logger, e error) Logger { + return l.AddContext("attached_error", e.Error()) +} diff --git a/log/logctx_test.go b/log/logctx_test.go index 69d4360..086060e 100644 --- a/log/logctx_test.go +++ b/log/logctx_test.go @@ -63,4 +63,43 @@ func TestLogContext(t *testing.T) { }) } }) + + t.Run("attach error", func(t *testing.T) { + + var ( + errOne = fmt.Errorf("error one") + errTwo = fmt.Errorf("error two") + ) + + for _, tc := range []struct { + m string + errs []error + err error + }{ + { + m: "single call", + errs: []error{errOne}, + err: errOne, + }, + { + m: "multiple calls overwrite", + errs: []error{errOne, errTwo}, + err: errTwo, + }, + } { + t.Run(tc.m, func(t *testing.T) { + var buff bytes.Buffer + logger := log.NewLogger(&buff) + + currentLogger := logger + for _, err := range tc.errs { + currentLogger = log.AttachError(currentLogger, err) + } + currentLogger.Info("something") + + test.Includes(t, + fmt.Sprintf("\"attached_error\":%q", tc.err.Error()), buff.String()) + }) + } + }) }