diff --git a/benchmarks/zap_test.go b/benchmarks/zap_test.go index 84784152c..0abb56e87 100644 --- a/benchmarks/zap_test.go +++ b/benchmarks/zap_test.go @@ -134,6 +134,7 @@ func fakeFields() []zap.Field { zap.Times("times", _tenTimes), zap.Object("user1", _oneUser), zap.Object("user2", _oneUser), + zap.Object("user3", nil), zap.Array("users", _tenUsers), zap.Error(errExample), } diff --git a/field.go b/field.go index 8441d1afb..1884afabc 100644 --- a/field.go +++ b/field.go @@ -398,6 +398,9 @@ func Durationp(key string, val *time.Duration) Field { // struct-like user-defined types to the logging context. The struct's // MarshalLogObject method is called lazily. func Object(key string, val zapcore.ObjectMarshaler) Field { + if val == nil { + return nilField(key) + } return Field{Key: key, Type: zapcore.ObjectMarshalerType, Interface: val} } diff --git a/field_test.go b/field_test.go index e145acf99..6b4d391c4 100644 --- a/field_test.go +++ b/field_test.go @@ -253,6 +253,7 @@ func TestFieldConstructors(t *testing.T) { {"Any:PtrUintptr", Any("k", &uintptrVal), Uintptr("k", uintptrVal)}, {"Any:ErrorNil", Any("k", nilErr), nilField("k")}, {"Namespace", Namespace("k"), Field{Key: "k", Type: zapcore.NamespaceType}}, + {"Object:Nil", Object("k", nil), nilField("k")}, } for _, tt := range tests { diff --git a/zapcore/field_test.go b/zapcore/field_test.go index 2b6d8c369..bbbc97d5f 100644 --- a/zapcore/field_test.go +++ b/zapcore/field_test.go @@ -158,6 +158,7 @@ func TestFields(t *testing.T) { {t: Uint8Type, i: 42, want: uint8(42)}, {t: UintptrType, i: 42, want: uintptr(42)}, {t: ReflectType, iface: users(2), want: users(2)}, + {t: ReflectType, iface: nil, want: nil}, {t: NamespaceType, want: map[string]interface{}{}}, {t: StringerType, iface: users(2), want: "2 users"}, {t: StringerType, iface: &obj{}, want: "obj"}, @@ -330,6 +331,16 @@ func TestEquals(t *testing.T) { b: zap.Object("k", zap.DictObject(zap.String("a", "d"))), want: false, }, + { + a: zap.Object("k", nil), + b: zap.Object("k", nil), + want: true, + }, + { + a: zap.Object("k", users(10)), + b: zap.Object("k", nil), + want: false, + }, } for _, tt := range tests {