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