Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add GetKeys to get event keys #527

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions event.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zerolog

import (
"encoding/json"
"fmt"
"net"
"os"
Expand Down Expand Up @@ -792,3 +793,23 @@ func (e *Event) MACAddr(key string, ha net.HardwareAddr) *Event {
e.buf = enc.AppendMACAddr(enc.AppendKey(e.buf, key), ha)
return e
}

// GetKeys returns the keys of the event.
// NOTE: This is an expensive operation and should be used sparingly.
func (e *Event) GetKeys() ([]string, error) {
if e == nil {
return nil, nil
}

var event map[string]interface{}
if err := json.Unmarshal(e.buf, &event); err != nil {
return nil, err
}

keys := make([]string, 0)
for key := range event {
keys = append(keys, key)
}

return keys, nil
}
23 changes: 23 additions & 0 deletions event_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build !binary_log
// +build !binary_log

package zerolog
Expand Down Expand Up @@ -63,3 +64,25 @@ func TestEvent_EmbedObjectWithNil(t *testing.T) {
t.Errorf("Event.EmbedObject() = %q, want %q", got, want)
}
}

func TestEvent_GetKeys(t *testing.T) {
var buf bytes.Buffer
e := newEvent(levelWriterAdapter{&buf}, DebugLevel)
e.Str("foo", "bar")
e.Int("baz", 42)
_ = e.write()

want := []string{"foo", "baz"}
got, err := e.GetKeys()
if err != nil {
t.Fatal(err)
}
if len(got) != len(want) {
t.Errorf("Event.GetKeys() = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("Event.GetKeys() = %v, want %v", got, want)
}
}
}