1 //go:build go1.21
2 // +build go1.21
3 4 /*
5 Copyright 2019 The logr Authors.
6 7 Licensed under the Apache License, Version 2.0 (the "License");
8 you may not use this file except in compliance with the License.
9 You may obtain a copy of the License at
10 11 http://www.apache.org/licenses/LICENSE-2.0
12 13 Unless required by applicable law or agreed to in writing, software
14 distributed under the License is distributed on an "AS IS" BASIS,
15 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 See the License for the specific language governing permissions and
17 limitations under the License.
18 */
19 20 package logr
21 22 import (
23 "context"
24 "fmt"
25 "log/slog"
26 )
27 28 // FromContext returns a Logger from ctx or an error if no Logger is found.
29 func FromContext(ctx context.Context) (Logger, error) {
30 v := ctx.Value(contextKey{})
31 if v == nil {
32 return Logger{}, notFoundError{}
33 }
34 35 switch v := v.(type) {
36 case Logger:
37 return v, nil
38 case *slog.Logger:
39 return FromSlogHandler(v.Handler()), nil
40 default:
41 // Not reached.
42 panic(fmt.Sprintf("unexpected value type for logr context key: %T", v))
43 }
44 }
45 46 // FromContextAsSlogLogger returns a slog.Logger from ctx or nil if no such Logger is found.
47 func FromContextAsSlogLogger(ctx context.Context) *slog.Logger {
48 v := ctx.Value(contextKey{})
49 if v == nil {
50 return nil
51 }
52 53 switch v := v.(type) {
54 case Logger:
55 return slog.New(ToSlogHandler(v))
56 case *slog.Logger:
57 return v
58 default:
59 // Not reached.
60 panic(fmt.Sprintf("unexpected value type for logr context key: %T", v))
61 }
62 }
63 64 // FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this
65 // returns a Logger that discards all log messages.
66 func FromContextOrDiscard(ctx context.Context) Logger {
67 if logger, err := FromContext(ctx); err == nil {
68 return logger
69 }
70 return Discard()
71 }
72 73 // NewContext returns a new Context, derived from ctx, which carries the
74 // provided Logger.
75 func NewContext(ctx context.Context, logger Logger) context.Context {
76 return context.WithValue(ctx, contextKey{}, logger)
77 }
78 79 // NewContextWithSlogLogger returns a new Context, derived from ctx, which carries the
80 // provided slog.Logger.
81 func NewContextWithSlogLogger(ctx context.Context, logger *slog.Logger) context.Context {
82 return context.WithValue(ctx, contextKey{}, logger)
83 }
84