Merge branch 'hh-111-method-attach-error' into 'master'

HH-111: add AttachError() to log package

See merge request go/kit!2
This commit is contained in:
Erik Winter 2019-10-04 09:24:09 +02:00
commit f4f995e24f
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())
})
}
})
}