From a41206ed2c49fc7c817f470f61c5082b124cf267 Mon Sep 17 00:00:00 2001 From: Ian Grayson Date: Mon, 8 Aug 2022 23:33:36 -0700 Subject: [PATCH] fix(otelzap): do not panic on invalid input (#69) --- otelzap/otelzap.go | 2 +- otelzap/otelzap_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/otelzap/otelzap.go b/otelzap/otelzap.go index 0bcb871..23efcca 100644 --- a/otelzap/otelzap.go +++ b/otelzap/otelzap.go @@ -528,7 +528,7 @@ func (s *SugaredLogger) logKVs( attrs := make([]attribute.KeyValue, 0, numAttr+len(kvs)) - for i := 0; i < len(kvs); i += 2 { + for i := 0; i < len(kvs)-1; i += 2 { if key, ok := kvs[i].(string); ok { attrs = append(attrs, otelutil.Attribute(key, kvs[i+1])) } diff --git a/otelzap/otelzap_test.go b/otelzap/otelzap_test.go index 2546975..3107ddd 100644 --- a/otelzap/otelzap_test.go +++ b/otelzap/otelzap_test.go @@ -265,6 +265,36 @@ func TestOtelZap(t *testing.T) { requireCodeAttrs(t, m) }, }, + { + log: func(ctx context.Context, log *Logger) { + log.Sugar().InfowContext(ctx, "hello", "foo", "bar") + }, + require: func(t *testing.T, event sdktrace.Event) { + m := attrMap(event.Attributes) + + sev, ok := m[logSeverityKey] + require.True(t, ok) + require.Equal(t, "INFO", sev.AsString()) + + msg, ok := m[logMessageKey] + require.True(t, ok) + require.Equal(t, "hello", msg.AsString()) + + foo, ok := m["foo"] + require.True(t, ok) + require.NotZero(t, foo.AsString()) + + requireCodeAttrs(t, m) + }, + }, + { + log: func(ctx context.Context, log *Logger) { + log.Sugar().InfowContext(ctx, "sugary logs require keyAndValues to come in pairs", "so this is invalid, but it shouldn't panic") + }, + require: func(t *testing.T, event sdktrace.Event) { + // no panic? success! + }, + }, { log: func(ctx context.Context, log *Logger) { log.Sugar().Ctx(ctx).Errorf("hello %s", "world")