diff --git a/slogger/README.md b/slogger/README.md index 0d6457e..73dd5b5 100644 --- a/slogger/README.md +++ b/slogger/README.md @@ -246,7 +246,8 @@ func LogAttrs(ctx context.Context, level slog.Level, msg string, attrs ...slog.A ``` - `ToContext` puts the logger into the context, `FromContext` takes it from - there. If the context has no logger, `slog.Default()` is used. + there. If the context has no logger, or the logger in it is nil, + `slog.Default()` is used. - `With` returns a derived context with the given attributes bound to it: they are added to every record written with that context. Without the arguments it returns the context unchanged. diff --git a/slogger/ctxlog/ctxlog.go b/slogger/ctxlog/ctxlog.go index 01e81e2..4f43776 100644 --- a/slogger/ctxlog/ctxlog.go +++ b/slogger/ctxlog/ctxlog.go @@ -14,7 +14,7 @@ func ToContext(ctx context.Context, logger *slog.Logger) context.Context { } func FromContext(ctx context.Context) *slog.Logger { - if l, ok := ctx.Value(loggerKey{}).(*slog.Logger); ok { + if l, ok := ctx.Value(loggerKey{}).(*slog.Logger); ok && l != nil { return l } return slog.Default() @@ -36,6 +36,7 @@ func Error(ctx context.Context, msg string, args ...any) { FromContext(ctx).ErrorContext(ctx, msg, args...) } +// With returns a copy of ctx carrying a logger with the given attributes. func With(ctx context.Context, args ...any) context.Context { if len(args) == 0 { return ctx diff --git a/slogger/ctxlog/ctxlog_test.go b/slogger/ctxlog/ctxlog_test.go index e753350..f2fc525 100644 --- a/slogger/ctxlog/ctxlog_test.go +++ b/slogger/ctxlog/ctxlog_test.go @@ -42,6 +42,14 @@ func TestFromContext_Default(t *testing.T) { assert.Same(t, slog.Default(), FromContext(t.Context())) } +func TestFromContext_NilLogger(t *testing.T) { + t.Parallel() + + ctx := ToContext(t.Context(), nil) + + assert.Same(t, slog.Default(), FromContext(ctx)) +} + func TestLogs(t *testing.T) { t.Parallel()