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
This commit is contained in:
Victor Alves 2019-09-26 14:41:18 +02:00
parent 38a0889c15
commit bb2bad1ea8
2 changed files with 45 additions and 0 deletions

View File

@ -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())
}

View File

@ -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())
})
}
})
}