-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.go
40 lines (32 loc) · 1.01 KB
/
context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package slogx
import (
"context"
"io"
"log/slog"
)
type contextKey struct{}
var nilLogger = slog.New(slog.NewTextHandler(io.Discard, nil))
// Ctx retrieves an attached slog.Logger from the context.
// If no logger is attached, a logger with io.Discard will be returned.
func Ctx(ctx context.Context) *slog.Logger {
raw := ctx.Value(contextKey{})
if raw == nil {
return nilLogger
}
logger, ok := raw.(*slog.Logger)
if !ok {
return nilLogger
}
return logger
}
// WithContext attaches a slog.Logger to the provided context. A copy of the provided
// logger is made to provide isolation.
func WithContext(ctx context.Context, logger *slog.Logger) context.Context {
lCopy := *logger
return context.WithValue(ctx, contextKey{}, &lCopy)
}
// With attaches given attributes to the slog.Logger found inside the context.
// If there is no logger on the context, it will attach a logger with io.Discard.
func With(ctx context.Context, args ...any) context.Context {
return WithContext(ctx, Ctx(ctx).With(args...))
}