Add AnErr field type
This commit is contained in:
parent
67803eb791
commit
49d553c9b8
|
@ -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 {
|
||||
|
|
11
event.go
11
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 {
|
||||
|
|
9
field.go
9
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 {
|
||||
|
|
|
@ -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).
|
||||
|
|
Loading…
Reference in New Issue