Skip to content

Commit

Permalink
otelzap: Implement Write method (#5620)
Browse files Browse the repository at this point in the history
Part of
#5191

Pre-work
#5279

This PR partially implements `Write` method

Co-authored-by: Robert Pająk <[email protected]>
  • Loading branch information
khushijain21 and pellared authored May 23, 2024
1 parent 4991263 commit 720adbc
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
16 changes: 15 additions & 1 deletion bridges/otelzap/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,18 +136,32 @@ func (o *Core) Write(ent zapcore.Entry, fields []zapcore.Field) error {
r.SetBody(log.StringValue(ent.Message))
r.SetSeverity(convertLevel(ent.Level))

// TODO: Handle attributes passed via fields (exceptions: context.Context and zap.Namespace).
// TODO: Handle attributes passed via With (exceptions: context.Context and zap.Namespace).
// TODO: Handle context.Context containing trace context.
// TODO: Handle zap.Namespace.
// TODO: Handle zap.Object.
// TODO: Handle zap.Array.
// TODO: Handle ent.LoggerName.

if len(fields) > 0 {
attrbuf := convertField(fields)
r.AddAttributes(attrbuf...)
}

o.logger.Emit(context.Background(), r)
return nil
}

func convertField(fields []zapcore.Field) []log.KeyValue {
// TODO: Use objectEncoder from a pool instead of newObjectEncoder.
enc := newObjectEncoder(len(fields))
for _, field := range fields {
field.AddTo(enc)
}

return enc.kv
}

func convertLevel(level zapcore.Level) log.Severity {
switch level {
case zapcore.DebugLevel:
Expand Down
11 changes: 9 additions & 2 deletions bridges/otelzap/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,26 @@ import (
var (
testMessage = "log message"
loggerName = "name"
testKey = "key"
testValue = "value"
)

func TestCore(t *testing.T) {
rec := logtest.NewRecorder()
zc := NewCore(loggerName, WithLoggerProvider(rec))
logger := zap.New(zc)

logger.Info(testMessage)
logger.Info(testMessage, zap.String(testKey, testValue))

// TODO (#5580): Not sure why index 1 is populated with results and not 0.
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, testKey, string(kv.Key))
assert.Equal(t, testValue, value2Result(kv.Value))
return true
})
}

func TestCoreEnabled(t *testing.T) {
Expand Down

0 comments on commit 720adbc

Please sign in to comment.