diff --git a/entry.go b/entry.go index b9206de..c0f398f 100644 --- a/entry.go +++ b/entry.go @@ -8,7 +8,7 @@ import ( "time" ) -// Defines the key when adding error using WithError. +// Defines the key when adding errors using WithError. var ErrorKey = "error" // An entry is the final or intermediate Logrus logging entry. It contains all @@ -56,7 +56,7 @@ func (entry *Entry) String() (string, error) { return reader.String(), err } -// Add an error as single field (with key "error") to the Entry. +// Add an error as single field (using the key defined in ErrorKey) to the Entry. func (entry *Entry) WithError(err error) *Entry { return entry.WithField(ErrorKey, err) } diff --git a/entry_test.go b/entry_test.go index a824e64..99c3b41 100644 --- a/entry_test.go +++ b/entry_test.go @@ -10,16 +10,25 @@ import ( func TestEntryWithError(t *testing.T) { + assert := assert.New(t) + + defer func() { + ErrorKey = "error" + }() + err := fmt.Errorf("kaboom at layer %d", 4711) + assert.Equal(err, WithError(err).Data["error"]) + logger := New() logger.Out = &bytes.Buffer{} entry := NewEntry(logger) - assert.Equal(t, err, entry.WithError(err).Data["error"]) + assert.Equal(err, entry.WithError(err).Data["error"]) ErrorKey = "err" - assert.Equal(t, err, entry.WithError(err).Data["err"]) + + assert.Equal(err, entry.WithError(err).Data["err"]) } diff --git a/exported.go b/exported.go index a67e1b8..9a0120a 100644 --- a/exported.go +++ b/exported.go @@ -48,6 +48,11 @@ func AddHook(hook Hook) { std.Hooks.Add(hook) } +// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +func WithError(err error) *Entry { + return std.WithField(ErrorKey, err) +} + // WithField creates an entry from the standard logger and adds a field to // it. If you want multiple fields, use `WithFields`. //