master
go 27 lines 610 Bytes
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package logger
4
5 import "context"
6
7 type contextKey struct{}
8
9 // ContextWithLogger attaches a logger to a context.
10 func ContextWithLogger(ctx context.Context, log *Logger) context.Context {
11 if ctx == nil {
12 ctx = context.Background()
13 }
14 if log == nil {
15 return ctx
16 }
17 return context.WithValue(ctx, contextKey{}, log)
18 }
19
20 // LoggerFromContext returns a logger attached to a context.
21 func LoggerFromContext(ctx context.Context) (*Logger, bool) {
22 if ctx == nil {
23 return nil, false
24 }
25 log, ok := ctx.Value(contextKey{}).(*Logger)
26 return log, ok && log != nil
27 }