diff --git a/entry.go b/entry.go index 17fe6f7..b9206de 100644 --- a/entry.go +++ b/entry.go @@ -8,6 +8,9 @@ import ( "time" ) +// Defines the key when adding error using WithError. +var ErrorKey = "error" + // An entry is the final or intermediate Logrus logging entry. It contains all // the fields passed with WithField{,s}. It's finally logged when Debug, Info, // Warn, Error, Fatal or Panic is called on it. These objects can be reused and @@ -53,6 +56,11 @@ func (entry *Entry) String() (string, error) { return reader.String(), err } +// Add an error as single field (with key "error") to the Entry. +func (entry *Entry) WithError(err error) *Entry { + return entry.WithField(ErrorKey, err) +} + // Add a single field to the Entry. func (entry *Entry) WithField(key string, value interface{}) *Entry { return entry.WithFields(Fields{key: value}) diff --git a/entry_test.go b/entry_test.go index 98717df..a824e64 100644 --- a/entry_test.go +++ b/entry_test.go @@ -8,6 +8,21 @@ import ( "github.com/stretchr/testify/assert" ) +func TestEntryWithError(t *testing.T) { + + err := fmt.Errorf("kaboom at layer %d", 4711) + + logger := New() + logger.Out = &bytes.Buffer{} + entry := NewEntry(logger) + + assert.Equal(t, err, entry.WithError(err).Data["error"]) + + ErrorKey = "err" + assert.Equal(t, err, entry.WithError(err).Data["err"]) + +} + func TestEntryPanicln(t *testing.T) { errBoom := fmt.Errorf("boom time")