context_slog.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. "fmt"
  19. "log/slog"
  20. )
  21. // FromContext returns a Logger from ctx or an error if no Logger is found.
  22. func FromContext(ctx context.Context) (Logger, error) {
  23. v := ctx.Value(contextKey{})
  24. if v == nil {
  25. return Logger{}, notFoundError{}
  26. }
  27. switch v := v.(type) {
  28. case Logger:
  29. return v, nil
  30. case *slog.Logger:
  31. return FromSlogHandler(v.Handler()), nil
  32. default:
  33. // Not reached.
  34. panic(fmt.Sprintf("unexpected value type for logr context key: %T", v))
  35. }
  36. }
  37. // FromContextAsSlogLogger returns a slog.Logger from ctx or nil if no such Logger is found.
  38. func FromContextAsSlogLogger(ctx context.Context) *slog.Logger {
  39. v := ctx.Value(contextKey{})
  40. if v == nil {
  41. return nil
  42. }
  43. switch v := v.(type) {
  44. case Logger:
  45. return slog.New(ToSlogHandler(v))
  46. case *slog.Logger:
  47. return v
  48. default:
  49. // Not reached.
  50. panic(fmt.Sprintf("unexpected value type for logr context key: %T", v))
  51. }
  52. }
  53. // FromContextOrDiscard returns a Logger from ctx. If no Logger is found, this
  54. // returns a Logger that discards all log messages.
  55. func FromContextOrDiscard(ctx context.Context) Logger {
  56. if logger, err := FromContext(ctx); err == nil {
  57. return logger
  58. }
  59. return Discard()
  60. }
  61. // NewContext returns a new Context, derived from ctx, which carries the
  62. // provided Logger.
  63. func NewContext(ctx context.Context, logger Logger) context.Context {
  64. return context.WithValue(ctx, contextKey{}, logger)
  65. }
  66. // NewContextWithSlogLogger returns a new Context, derived from ctx, which carries the
  67. // provided slog.Logger.
  68. func NewContextWithSlogLogger(ctx context.Context, logger *slog.Logger) context.Context {
  69. return context.WithValue(ctx, contextKey{}, logger)
  70. }