diff --git a/context.go b/context.go index 6a79c00..ce23514 100644 --- a/context.go +++ b/context.go @@ -26,6 +26,12 @@ func (c Context) Str(key, val string) Context { return c } +// AnErr adds the field key with err as a string to the logger context. +func (c Context) AnErr(key string, err error) Context { + c.l.context = appendErrorKey(c.l.context, key, err) + return c +} + // Err adds the field "error" with err as a string to the logger context. // To customize the key name, change zerolog.ErrorFieldName. func (c Context) Err(err error) Context { diff --git a/event.go b/event.go index 9bb3f56..12779b4 100644 --- a/event.go +++ b/event.go @@ -116,7 +116,18 @@ func (e *Event) Str(key, val string) *Event { return e } +// AnErr adds the field key with err as a string to the *Event context. +// If err is nil, no field is added. +func (e *Event) AnErr(key string, err error) *Event { + if !e.enabled { + return e + } + e.buf = appendErrorKey(e.buf, key, err) + return e +} + // Err adds the field "error" with err as a string to the *Event context. +// If err is nil, no field is added. // To customize the key name, change zerolog.ErrorFieldName. func (e *Event) Err(err error) *Event { if !e.enabled { diff --git a/field.go b/field.go index 0867119..0c0e5b0 100644 --- a/field.go +++ b/field.go @@ -19,8 +19,15 @@ func appendString(dst []byte, key, val string) []byte { return appendJSONString(appendKey(dst, key), val) } +func appendErrorKey(dst []byte, key string, err error) []byte { + if err == nil { + return dst + } + return appendJSONString(appendKey(dst, key), err.Error()) +} + func appendError(dst []byte, err error) []byte { - return appendJSONString(appendKey(dst, ErrorFieldName), err.Error()) + return appendErrorKey(dst, ErrorFieldName, err) } func appendBool(dst []byte, key string, val bool) []byte { diff --git a/log_test.go b/log_test.go index 21fd93e..49a233d 100644 --- a/log_test.go +++ b/log_test.go @@ -76,6 +76,7 @@ func TestWith(t *testing.T) { out := &bytes.Buffer{} log := New(out).With(). Str("foo", "bar"). + AnErr("some_err", nil). Err(errors.New("some error")). Bool("bool", true). Int("int", 1). @@ -103,6 +104,7 @@ func TestFields(t *testing.T) { log := New(out) log.Log(). Str("foo", "bar"). + AnErr("some_err", nil). Err(errors.New("some error")). Bool("bool", true). Int("int", 1). @@ -129,6 +131,7 @@ func TestFieldsDisabled(t *testing.T) { log := New(out).Level(InfoLevel) log.Debug(). Str("foo", "bar"). + AnErr("some_err", nil). Err(errors.New("some error")). Bool("bool", true). Int("int", 1).