Skip to content

Commit

Permalink
otelzap: Implement with method
Browse files Browse the repository at this point in the history
  • Loading branch information
khushijain21 committed May 23, 2024
1 parent f18c842 commit b7406f0
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
21 changes: 19 additions & 2 deletions bridges/otelzap/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package otelzap // import "go.opentelemetry.io/contrib/bridges/otelzap"

import (
"context"
"slices"

"go.uber.org/zap/zapcore"

Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
16 changes: 16 additions & 0 deletions bridges/otelzap/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit b7406f0

Please sign in to comment.