Skip to content

Commit

Permalink
add: ContextLogger Interface LogObjectMarshaler
Browse files Browse the repository at this point in the history
  • Loading branch information
Hyuga-Tsukui committed Dec 7, 2023
1 parent 7fa45a4 commit 69c2fae
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
3 changes: 3 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,9 @@ func (c Context) Durs(key string, d []time.Duration) Context {

// Interface adds the field key with obj marshaled using reflection.
func (c Context) Interface(key string, i interface{}) Context {
if obj, ok := i.(LogObjectMarshaler); ok {
return c.Object(key, obj)
}
c.l.context = enc.AppendInterface(enc.AppendKey(c.l.context, key), i)
return c
}
Expand Down
29 changes: 29 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zerolog

import (
"bytes"
"context"
"io"
"reflect"
Expand Down Expand Up @@ -68,3 +69,31 @@ func TestCtxDisabled(t *testing.T) {
t.Error("WithContext did not override logger with a disabled logger")
}
}

type logObjectMarshalerImpl struct {
name string
age int
}

func (t logObjectMarshalerImpl) MarshalZerologObject(e *Event) {
e.Str("name", "custom_value").Int("age", t.age)
}

func Test_InterfaceLogObjectMarshaler(t *testing.T) {
var buf bytes.Buffer
log := New(&buf)
ctx := log.WithContext(context.Background())

log2 := Ctx(ctx)

withLog := log2.With().Interface("obj", &logObjectMarshalerImpl{
name: "foo",
age: 29,
}).Logger()

withLog.Info().Msg("test")

if got, want := buf.String(), `{"level":"info","obj":{"name":"custom_value","age":29},"message":"test"}`+"\n"; got != want {
t.Errorf("got %q, want %q", got, want)
}
}

0 comments on commit 69c2fae

Please sign in to comment.