-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
35 lines (28 loc) · 982 Bytes
/
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
package slogx
import (
"context"
"log/slog"
)
type contextKey int
const (
contextKeyLog contextKey = iota
contextKeyHandler
)
// NewContextWithHandler returns a new Context that carries value handler.
func NewContextWithHandler(ctx context.Context, handler slog.Handler) context.Context {
return context.WithValue(ctx, contextKeyHandler, handler)
}
// HandlerFromContext returns a Handler value stored in ctx if exists or nil.
func HandlerFromContext(ctx context.Context) slog.Handler {
handler, _ := ctx.Value(contextKeyHandler).(slog.Handler)
return handler
}
// NewContextWithLogger returns a new Context that carries value log.
func NewContextWithLogger(ctx context.Context, log *slog.Logger) context.Context {
return context.WithValue(ctx, contextKeyLog, log)
}
// LoggerFromContext returns a Logger value stored in ctx if exists or nil.
func LoggerFromContext(ctx context.Context) *slog.Logger {
log, _ := ctx.Value(contextKeyLog).(*slog.Logger)
return log
}