context_noslog.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. //go:build !go1.21
  2. // +build !go1.21
  3. /*
  4. Copyright 2019 The logr Authors.
  5. Licensed under the Apache License, Version 2.0 (the "License");
  6. you may not use this file except in compliance with the License.
  7. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. */
  15. package logr
  16. import (
  17. "context"
  18. )
  19. // FromContext returns a Logger from ctx or an error if no Logger is found.
  20. func FromContext(ctx context.Context) (Logger, error) {
  21. if v, ok := ctx.Value(contextKey{}).(Logger); ok {
  22. return v, nil
  23. }
  24. return Logger{}, notFoundError{}
  25. }
  26. // FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this
  27. // returns a Logger that discards all log messages.
  28. func FromContextOrDiscard(ctx context.Context) Logger {
  29. if v, ok := ctx.Value(contextKey{}).(Logger); ok {
  30. return v
  31. }
  32. return Discard()
  33. }
  34. // NewContext returns a new Context, derived from ctx, which carries the
  35. // provided Logger.
  36. func NewContext(ctx context.Context, logger Logger) context.Context {
  37. return context.WithValue(ctx, contextKey{}, logger)
  38. }