Skip to content

Commit

Permalink
Adding Event.Type(...) method to log the type of an object (#437)
Browse files Browse the repository at this point in the history
Co-authored-by: Mario Cormier <[email protected]>
  • Loading branch information
w3aponx and Mario Cormier authored Oct 18, 2022
1 parent 55aaf04 commit 89617ff
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
9 changes: 9 additions & 0 deletions event.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 9 additions & 0 deletions internal/json/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"fmt"
"math"
"net"
"reflect"
"strconv"
)

Expand Down Expand Up @@ -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, "<nil>")
}
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 {
Expand Down
22 changes: 22 additions & 0 deletions internal/json/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(`"<nil>"`)},
{"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
Expand Down

0 comments on commit 89617ff

Please sign in to comment.