-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathctx.go
More file actions
35 lines (28 loc) · 791 Bytes
/
ctx.go
File metadata and controls
35 lines (28 loc) · 791 Bytes
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 slogctx
import (
"context"
"log/slog"
"github.com/go-logr/logr"
)
// NewCtx returns a copy of ctx with the logger attached.
// The parent context will be unaffected.
func NewCtx(parent context.Context, logger *slog.Logger) context.Context {
if parent == nil {
parent = context.Background()
}
return logr.NewContextWithSlogLogger(parent, logger)
}
// FromCtx returns the slog.FromCtx associated with the ctx.
// If no logger is associated, or the logger or ctx are nil,
// slog.Default() is returned.
// This function will convert a logr.Logger to a *slog.Logger only if necessary.
func FromCtx(ctx context.Context) *slog.Logger {
if ctx == nil {
return slog.Default()
}
l := logr.FromContextAsSlogLogger(ctx)
if l == nil {
return slog.Default()
}
return l
}