From 327c974f0ea396360bdf9f2d845dcc110f3e9e21 Mon Sep 17 00:00:00 2001 From: Kit Patella Date: Thu, 24 Oct 2024 16:40:10 -0700 Subject: [PATCH] make sure logger.From can handle a nil context Signed-off-by: Kit Patella --- src/pkg/logger/logger.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/pkg/logger/logger.go b/src/pkg/logger/logger.go index 8008129462..af61985981 100644 --- a/src/pkg/logger/logger.go +++ b/src/pkg/logger/logger.go @@ -176,11 +176,14 @@ func WithContext(ctx context.Context, logger *slog.Logger) context.Context { // From takes a context and reads out a *slog.Logger. If From does not find a value it will return a discarding logger // similar to log-format "none". func From(ctx context.Context) *slog.Logger { + // Check that we have a ctx + if ctx == nil { + return newEmpty() + } // Grab value from key log := ctx.Value(defaultCtxKey) if log == nil { - h := slog.NewTextHandler(DestinationNone, &slog.HandlerOptions{}) - return slog.New(h) + return newEmpty() } // Ensure our value is a *slog.Logger before we cast. @@ -193,6 +196,12 @@ func From(ctx context.Context) *slog.Logger { } } +// newDiscard returns a logger without any settings that goes to io.Discard +func newEmpty() *slog.Logger { + h := slog.NewTextHandler(DestinationNone, &slog.HandlerOptions{}) + return slog.New(h) +} + // Default retrieves a logger from the package default. This is intended as a fallback when a logger cannot easily be // passed in as a dependency, like when developing a new function. Use it like you would use context.TODO(). func Default() *slog.Logger {