Skip to content

Commit

Permalink
make sure logger.From can handle a nil context
Browse files Browse the repository at this point in the history
Signed-off-by: Kit Patella <[email protected]>
  • Loading branch information
mkcp committed Oct 24, 2024
1 parent 7b387e8 commit 327c974
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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 {
Expand Down

0 comments on commit 327c974

Please sign in to comment.