Skip to content

Commit

Permalink
zap context
Browse files Browse the repository at this point in the history
  • Loading branch information
khushijain21 committed Jun 3, 2024
1 parent 48524de commit 3ccf3fb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
15 changes: 9 additions & 6 deletions bridges/otelzap/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,9 @@ func (o *Core) Enabled(level zapcore.Level) bool {
func (o *Core) With(fields []zapcore.Field) zapcore.Core {
cloned := o.clone()
if len(fields) > 0 {
cloned.attr = append(cloned.attr, convertField(&cloned.ctx, fields)...)
var attrbuf []log.KeyValue
cloned.ctx, attrbuf = convertField(cloned.ctx, fields)
cloned.attr = append(cloned.attr, attrbuf...)
}
return cloned
}
Expand Down Expand Up @@ -152,31 +154,32 @@ func (o *Core) Write(ent zapcore.Entry, fields []zapcore.Field) error {
r.SetSeverity(convertLevel(ent.Level))

// 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 ent.LoggerName.

r.AddAttributes(o.attr...)
if len(fields) > 0 {
r.AddAttributes(convertField(&o.ctx, fields)...)
var attrbuf []log.KeyValue
o.ctx, attrbuf = convertField(o.ctx, fields)
r.AddAttributes(attrbuf...)
}

o.logger.Emit(o.ctx, r)
return nil
}

func convertField(ctx *context.Context, fields []zapcore.Field) []log.KeyValue {
func convertField(ctx context.Context, fields []zapcore.Field) (context.Context, []log.KeyValue) {
// TODO: Use objectEncoder from a pool instead of newObjectEncoder.
enc := newObjectEncoder(len(fields))
for _, field := range fields {
if ctxFld, ok := field.Interface.(context.Context); ok {
*ctx = ctxFld
ctx = ctxFld
continue

Check warning on line 177 in bridges/otelzap/core.go

View check run for this annotation

Codecov / codecov/patch

bridges/otelzap/core.go#L176-L177

Added lines #L176 - L177 were not covered by tests
}
field.AddTo(enc)
}

return enc.kv
return ctx, enc.kv
}

func convertLevel(level zapcore.Level) log.Severity {
Expand Down
3 changes: 3 additions & 0 deletions bridges/otelzap/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ func TestCore(t *testing.T) {

rec.Reset()

// TODO WriteContext
// TOOD WithContext

// test child logger with accumulated fields
t.Run("With", func(t *testing.T) {
testCases := [][]string{{"test1", "value1"}, {"test2", "value2"}}
Expand Down

0 comments on commit 3ccf3fb

Please sign in to comment.