Skip to content

Commit 89617ff

Browse files
w3aponxMario Cormier
andauthored
Adding Event.Type(...) method to log the type of an object (#437)
Co-authored-by: Mario Cormier <mcormier@rossvideo.com>
1 parent 55aaf04 commit 89617ff

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

event.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -719,6 +719,15 @@ func (e *Event) Interface(key string, i interface{}) *Event {
719719
return e
720720
}
721721

722+
// Type adds the field key with val's type using reflection.
723+
func (e *Event) Type(key string, val interface{}) *Event {
724+
if e == nil {
725+
return e
726+
}
727+
e.buf = enc.AppendType(enc.AppendKey(e.buf, key), val)
728+
return e
729+
}
730+
722731
// CallerSkipFrame instructs any future Caller calls to skip the specified number of frames.
723732
// This includes those added via hooks from the context.
724733
func (e *Event) CallerSkipFrame(skip int) *Event {

internal/json/types.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"fmt"
55
"math"
66
"net"
7+
"reflect"
78
"strconv"
89
)
910

@@ -369,6 +370,14 @@ func (e Encoder) AppendInterface(dst []byte, i interface{}) []byte {
369370
return append(dst, marshaled...)
370371
}
371372

373+
// AppendType appends the parameter type (as a string) to the input byte slice.
374+
func (e Encoder) AppendType(dst []byte, i interface{}) []byte {
375+
if i == nil {
376+
return e.AppendString(dst, "<nil>")
377+
}
378+
return e.AppendString(dst, reflect.TypeOf(i).String())
379+
}
380+
372381
// AppendObjectData takes in an object that is already in a byte array
373382
// and adds it to the dst.
374383
func (Encoder) AppendObjectData(dst []byte, o []byte) []byte {

internal/json/types_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,28 @@ func Test_appendMac(t *testing.T) {
166166
}
167167
}
168168

169+
func Test_appendType(t *testing.T) {
170+
typeTests := []struct {
171+
label string
172+
input interface{}
173+
want []byte
174+
}{
175+
{"int", 42, []byte(`"int"`)},
176+
{"MAC", net.HardwareAddr{0x12, 0x34, 0x00, 0x00, 0x90, 0xab}, []byte(`"net.HardwareAddr"`)},
177+
{"float64", float64(2.50), []byte(`"float64"`)},
178+
{"nil", nil, []byte(`"<nil>"`)},
179+
{"bool", true, []byte(`"bool"`)},
180+
}
181+
182+
for _, tt := range typeTests {
183+
t.Run(tt.label, func(t *testing.T) {
184+
if got := enc.AppendType([]byte{}, tt.input); !reflect.DeepEqual(got, tt.want) {
185+
t.Errorf("appendType() = %s, want %s", got, tt.want)
186+
}
187+
})
188+
}
189+
}
190+
169191
func Test_appendObjectData(t *testing.T) {
170192
tests := []struct {
171193
dst []byte

0 commit comments

Comments
 (0)