Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

otelzap: Allow context injection via fields #5707

Merged
merged 13 commits into from
Jun 4, 2024
15 changes: 11 additions & 4 deletions bridges/otelzap/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@
type Core struct {
logger log.Logger
attr []log.KeyValue
ctx context.Context
}

// Compile-time check *Core implements zapcore.Core.
Expand All @@ -100,6 +101,7 @@
cfg := newConfig(opts)
return &Core{
logger: cfg.logger(name),
ctx: context.Background(),
}
}

Expand All @@ -114,7 +116,7 @@
func (o *Core) With(fields []zapcore.Field) zapcore.Core {
cloned := o.clone()
if len(fields) > 0 {
cloned.attr = append(cloned.attr, convertField(fields)...)
cloned.attr = append(cloned.attr, convertField(&cloned.ctx, fields)...)
}
return cloned
}
Expand All @@ -123,6 +125,7 @@
return &Core{
logger: o.logger,
attr: slices.Clone(o.attr),
ctx: o.ctx,
}
}

Expand Down Expand Up @@ -155,17 +158,21 @@

r.AddAttributes(o.attr...)
if len(fields) > 0 {
r.AddAttributes(convertField(fields)...)
r.AddAttributes(convertField(&o.ctx, fields)...)
}

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

func convertField(fields []zapcore.Field) []log.KeyValue {
func convertField(ctx *context.Context, fields []zapcore.Field) []log.KeyValue {
khushijain21 marked this conversation as resolved.
Show resolved Hide resolved
// 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
continue

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

View check run for this annotation

Codecov / codecov/patch

bridges/otelzap/core.go#L173-L174

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

Expand Down
Loading