Skip to content

Commit 027fe01

Browse files
lukedirtwalkerjuagargi
authored andcommitted
pkg/log: fix panic when using custom Logger (scionproto#4452)
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.
1 parent 9717dbb commit 027fe01

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

pkg/log/context.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,21 @@ func WithLabels(ctx context.Context, labels ...interface{}) (context.Context, Lo
6565

6666
func attachSpan(ctx context.Context, l Logger) Logger {
6767
if span := opentracing.SpanFromContext(ctx); span != nil {
68+
if optioner, ok := l.(interface{ WithOptions(...zap.Option) Logger }); ok {
69+
return Span{
70+
Logger: optioner.WithOptions(zap.AddCallerSkip(1)),
71+
Span: span,
72+
}
73+
}
74+
if il, ok := l.(*logger); ok {
75+
return Span{
76+
Logger: &logger{logger: il.logger.WithOptions(zap.AddCallerSkip(1))},
77+
Span: span,
78+
}
79+
}
80+
// Pessimistic fallback, we don't have access to the underlying zap logger:
6881
return Span{
69-
Logger: &logger{logger: l.(*logger).logger.WithOptions(zap.AddCallerSkip(1))},
82+
Logger: l,
7083
Span: span,
7184
}
7285
}

0 commit comments

Comments
 (0)