From 4b6ee96ca024ed7af8b32630fef653fb8b5cdf38 Mon Sep 17 00:00:00 2001 From: Lukas Vogel Date: Wed, 6 Dec 2023 16:06:03 +0100 Subject: [PATCH] pkg/log: fix panic when using custom Logger 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. --- pkg/log/context.go | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/pkg/log/context.go b/pkg/log/context.go index 32b949390f..d7c0813c80 100644 --- a/pkg/log/context.go +++ b/pkg/log/context.go @@ -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, } }