From 6973188a7402be93e3b27e318eac70d67cbbf1bd Mon Sep 17 00:00:00 2001 From: "Federico G. Schwindt" Date: Tue, 2 Nov 2021 00:53:02 +0000 Subject: [PATCH] Add support for dicts in array (#375) Fixes #111. --- array.go | 7 +++++++ array_test.go | 8 ++++++-- log_example_test.go | 8 ++++++-- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/array.go b/array.go index 0f7f53e..666dded 100644 --- a/array.go +++ b/array.go @@ -231,3 +231,10 @@ func (a *Array) MACAddr(ha net.HardwareAddr) *Array { a.buf = enc.AppendMACAddr(enc.AppendArrayDelim(a.buf), ha) return a } + +// Dict adds the dict Event to the array +func (a *Array) Dict(dict *Event) *Array { + dict.buf = enc.AppendEndMarker(dict.buf) + a.buf = append(enc.AppendArrayDelim(a.buf), dict.buf...) + return a +} diff --git a/array_test.go b/array_test.go index e8857e6..d37d8fb 100644 --- a/array_test.go +++ b/array_test.go @@ -27,8 +27,12 @@ func TestArray(t *testing.T) { RawJSON([]byte(`{"some":"json"}`)). Time(time.Time{}). IPAddr(net.IP{192, 168, 0, 10}). - Dur(0) - want := `[true,1,2,3,4,5,6,7,8,9,10,11.98122,12.987654321,"a","b","1f",{"some":"json"},"0001-01-01T00:00:00Z","192.168.0.10",0]` + Dur(0). + Dict(Dict(). + Str("bar", "baz"). + Int("n", 1), + ) + want := `[true,1,2,3,4,5,6,7,8,9,10,11.98122,12.987654321,"a","b","1f",{"some":"json"},"0001-01-01T00:00:00Z","192.168.0.10",0,{"bar":"baz","n":1}]` if got := decodeObjectToStr(a.write([]byte{})); got != want { t.Errorf("Array.write()\ngot: %s\nwant: %s", got, want) } diff --git a/log_example_test.go b/log_example_test.go index a41fdbb..2985b95 100644 --- a/log_example_test.go +++ b/log_example_test.go @@ -238,11 +238,15 @@ func ExampleEvent_Array() { Str("foo", "bar"). Array("array", zerolog.Arr(). Str("baz"). - Int(1), + Int(1). + Dict(zerolog.Dict(). + Str("bar", "baz"). + Int("n", 1), + ), ). Msg("hello world") - // Output: {"foo":"bar","array":["baz",1],"message":"hello world"} + // Output: {"foo":"bar","array":["baz",1,{"bar":"baz","n":1}],"message":"hello world"} } func ExampleEvent_Array_object() {