Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion slogger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 2 additions & 1 deletion slogger/ctxlog/ctxlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
Expand Down
8 changes: 8 additions & 0 deletions slogger/ctxlog/ctxlog_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
Loading