From b7406f0581cf6ceaf385cff1352956165bdbc746 Mon Sep 17 00:00:00 2001 From: khushijain21 Date: Thu, 23 May 2024 17:02:13 +0530 Subject: [PATCH] otelzap: Implement with method --- bridges/otelzap/core.go | 21 +++++++++++++++++++-- bridges/otelzap/core_test.go | 16 ++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/bridges/otelzap/core.go b/bridges/otelzap/core.go index 82680c233ba..28660684c3f 100644 --- a/bridges/otelzap/core.go +++ b/bridges/otelzap/core.go @@ -7,6 +7,7 @@ package otelzap // import "go.opentelemetry.io/contrib/bridges/otelzap" import ( "context" + "slices" "go.uber.org/zap/zapcore" @@ -88,6 +89,7 @@ func WithLoggerProvider(provider log.LoggerProvider) Option { // Core is a [zapcore.Core] that sends logging records to OpenTelemetry. type Core struct { logger log.Logger + attr []log.KeyValue } // Compile-time check *Core implements zapcore.Core. @@ -108,10 +110,21 @@ func (o *Core) Enabled(level zapcore.Level) bool { return o.logger.Enabled(context.Background(), r) } -// TODO // With adds structured context to the Core. func (o *Core) With(fields []zapcore.Field) zapcore.Core { - return o + clone := o.clone() + if len(fields) > 0 { + attrbuf := convertField(fields) + clone.attr = append(clone.attr, attrbuf...) + } + return clone +} + +func (o *Core) clone() *Core { + return &Core{ + logger: o.logger, + attr: slices.Clone(o.attr), + } } // TODO @@ -145,7 +158,11 @@ func (o *Core) Write(ent zapcore.Entry, fields []zapcore.Field) error { if len(fields) > 0 { attrbuf := convertField(fields) + attrbuf = slices.Grow(attrbuf, len(o.attr)) + attrbuf = append(attrbuf, o.attr...) r.AddAttributes(attrbuf...) + } else { + r.AddAttributes(o.attr...) } o.logger.Emit(context.Background(), r) diff --git a/bridges/otelzap/core_test.go b/bridges/otelzap/core_test.go index 1d7b519cce6..0c580ceced1 100644 --- a/bridges/otelzap/core_test.go +++ b/bridges/otelzap/core_test.go @@ -40,6 +40,22 @@ func TestCore(t *testing.T) { assert.Equal(t, testValue, value2Result(kv.Value)) return true }) + + rec.Reset() + + // test child logger with accumulated fields + childlogger := logger.With(zap.String("workplace", "otel")) + childlogger.Info(testMessage) + + got = rec.Result()[0].Records[0] + assert.Equal(t, testMessage, got.Body().AsString()) + assert.Equal(t, log.SeverityInfo, got.Severity()) + assert.Equal(t, 1, got.AttributesLen()) + got.WalkAttributes(func(kv log.KeyValue) bool { + assert.Equal(t, "workplace", string(kv.Key)) + assert.Equal(t, "otel", value2Result(kv.Value)) + return true + }) } func TestCoreEnabled(t *testing.T) {