| 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 |
) |
| 24 |
|
| 25 |
// FromContext returns a Logger from ctx or an error if no Logger is found. |
| 26 |
func FromContext(ctx context.Context) (Logger, error) { |
| 27 |
if v, ok := ctx.Value(contextKey{}).(Logger); ok { |
| 28 |
return v, nil |
| 29 |
} |
| 30 |
|
| 31 |
return Logger{}, notFoundError{} |
| 32 |
} |
| 33 |
|
| 34 |
// FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this |
| 35 |
// returns a Logger that discards all log messages. |
| 36 |
func FromContextOrDiscard(ctx context.Context) Logger { |
| 37 |
if v, ok := ctx.Value(contextKey{}).(Logger); ok { |
| 38 |
return v |
| 39 |
} |
| 40 |
|
| 41 |
return Discard() |
| 42 |
} |
| 43 |
|
| 44 |
// NewContext returns a new Context, derived from ctx, which carries the |
| 45 |
// provided Logger. |
| 46 |
func NewContext(ctx context.Context, logger Logger) context.Context { |
| 47 |
return context.WithValue(ctx, contextKey{}, logger) |
| 48 |
} |