From 89617ff99b2feb29ab2d8b6258fac9d671073792 Mon Sep 17 00:00:00 2001 From: Mario Cormier Date: Mon, 17 Oct 2022 20:51:54 -0400 Subject: [PATCH] Adding Event.Type(...) method to log the type of an object (#437) Co-authored-by: Mario Cormier --- event.go | 9 +++++++++ internal/json/types.go | 9 +++++++++ internal/json/types_test.go | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/event.go b/event.go index 0e2eaa68..eb5c90dd 100644 --- a/event.go +++ b/event.go @@ -719,6 +719,15 @@ func (e *Event) Interface(key string, i interface{}) *Event { return e } +// Type adds the field key with val's type using reflection. +func (e *Event) Type(key string, val interface{}) *Event { + if e == nil { + return e + } + e.buf = enc.AppendType(enc.AppendKey(e.buf, key), val) + return e +} + // CallerSkipFrame instructs any future Caller calls to skip the specified number of frames. // This includes those added via hooks from the context. func (e *Event) CallerSkipFrame(skip int) *Event { diff --git a/internal/json/types.go b/internal/json/types.go index ad7f7a88..ef3a2a7a 100644 --- a/internal/json/types.go +++ b/internal/json/types.go @@ -4,6 +4,7 @@ import ( "fmt" "math" "net" + "reflect" "strconv" ) @@ -369,6 +370,14 @@ func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte { return append(dst, marshaled...) } +// AppendType appends the parameter type (as a string) to the input byte slice. +func (e Encoder) AppendType(dst []byte, i interface{}) []byte { + if i == nil { + return e.AppendString(dst, "") + } + return e.AppendString(dst, reflect.TypeOf(i).String()) +} + // AppendObjectData takes in an object that is already in a byte array // and adds it to the dst. func (Encoder) AppendObjectData(dst []byte, o []byte) []byte { diff --git a/internal/json/types_test.go b/internal/json/types_test.go index 9a9d668b..26dc3e80 100644 --- a/internal/json/types_test.go +++ b/internal/json/types_test.go @@ -166,6 +166,28 @@ func Test_appendMac(t *testing.T) { } } +func Test_appendType(t *testing.T) { + typeTests := []struct { + label string + input interface{} + want []byte + }{ + {"int", 42, []byte(`"int"`)}, + {"MAC", net.HardwareAddr{0x12, 0x34, 0x00, 0x00, 0x90, 0xab}, []byte(`"net.HardwareAddr"`)}, + {"float64", float64(2.50), []byte(`"float64"`)}, + {"nil", nil, []byte(`""`)}, + {"bool", true, []byte(`"bool"`)}, + } + + for _, tt := range typeTests { + t.Run(tt.label, func(t *testing.T) { + if got := enc.AppendType([]byte{}, tt.input); !reflect.DeepEqual(got, tt.want) { + t.Errorf("appendType() = %s, want %s", got, tt.want) + } + }) + } +} + func Test_appendObjectData(t *testing.T) { tests := []struct { dst []byte