-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcontext.go
38 lines (31 loc) · 822 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
36
37
38
package xslog
import (
"context"
"golang.org/x/exp/slog"
)
type ctxKey int
const (
ctxLoggerKey ctxKey = iota
)
// WithLogger returns a new context that is bound with logger.
func WithLogger(ctx context.Context, logger *slog.Logger) context.Context {
if ctx == nil || logger == nil {
return ctx
}
return context.WithValue(ctx, ctxLoggerKey, logger)
}
// ContextLogger returns slog logger from ctx.
func ContextLogger(ctx context.Context) *slog.Logger {
if ctx == nil {
return nil
}
logger, ok := ctx.Value(ctxLoggerKey).(*slog.Logger)
if !ok {
return nil
}
return logger
}
// TransferLogger returns a new context that is bound with slog logger from src and based on dst.
func TransferLogger(dst context.Context, src context.Context) context.Context {
return WithLogger(dst, ContextLogger(src))
}