Skip to content

Commit

Permalink
pkg/log: fix panic when using custom Logger (#4452)
Browse files Browse the repository at this point in the history
log.FromCtx could panic if a custom Logger was used and a span was
present in the context. This commit allows the custom logger to
implement the `WithOptions(...zap.Option) Logger` method so that the
CallerSkip can still be applied. In case the logger can't be casted to
anything the caller skip is not applied, but we also don't panic
anymore.
  • Loading branch information
lukedirtwalker authored Dec 7, 2023
1 parent 85b8a13 commit b4e65a6
Showing 1 changed file with 14 additions and 1 deletion.
15 changes: 14 additions & 1 deletion pkg/log/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,21 @@ func WithLabels(ctx context.Context, labels ...interface{}) (context.Context, Lo

func attachSpan(ctx context.Context, l Logger) Logger {
if span := opentracing.SpanFromContext(ctx); span != nil {
if optioner, ok := l.(interface{ WithOptions(...zap.Option) Logger }); ok {
return Span{
Logger: optioner.WithOptions(zap.AddCallerSkip(1)),
Span: span,
}
}
if il, ok := l.(*logger); ok {
return Span{
Logger: &logger{logger: il.logger.WithOptions(zap.AddCallerSkip(1))},
Span: span,
}
}
// Pessimistic fallback, we don't have access to the underlying zap logger:
return Span{
Logger: &logger{logger: l.(*logger).logger.WithOptions(zap.AddCallerSkip(1))},
Logger: l,
Span: span,
}
}
Expand Down

0 comments on commit b4e65a6

Please sign in to comment.