slogsink.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. //go:build go1.21
  2. // +build go1.21
  3. /*
  4. Copyright 2023 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. "log/slog"
  19. "runtime"
  20. "time"
  21. )
  22. var (
  23. _ LogSink = &slogSink{}
  24. _ CallDepthLogSink = &slogSink{}
  25. _ Underlier = &slogSink{}
  26. )
  27. // Underlier is implemented by the LogSink returned by NewFromLogHandler.
  28. type Underlier interface {
  29. // GetUnderlying returns the Handler used by the LogSink.
  30. GetUnderlying() slog.Handler
  31. }
  32. const (
  33. // nameKey is used to log the `WithName` values as an additional attribute.
  34. nameKey = "logger"
  35. // errKey is used to log the error parameter of Error as an additional attribute.
  36. errKey = "err"
  37. )
  38. type slogSink struct {
  39. callDepth int
  40. name string
  41. handler slog.Handler
  42. }
  43. func (l *slogSink) Init(info RuntimeInfo) {
  44. l.callDepth = info.CallDepth
  45. }
  46. func (l *slogSink) GetUnderlying() slog.Handler {
  47. return l.handler
  48. }
  49. func (l *slogSink) WithCallDepth(depth int) LogSink {
  50. newLogger := *l
  51. newLogger.callDepth += depth
  52. return &newLogger
  53. }
  54. func (l *slogSink) Enabled(level int) bool {
  55. return l.handler.Enabled(context.Background(), slog.Level(-level))
  56. }
  57. func (l *slogSink) Info(level int, msg string, kvList ...interface{}) {
  58. l.log(nil, msg, slog.Level(-level), kvList...)
  59. }
  60. func (l *slogSink) Error(err error, msg string, kvList ...interface{}) {
  61. l.log(err, msg, slog.LevelError, kvList...)
  62. }
  63. func (l *slogSink) log(err error, msg string, level slog.Level, kvList ...interface{}) {
  64. var pcs [1]uintptr
  65. // skip runtime.Callers, this function, Info/Error, and all helper functions above that.
  66. runtime.Callers(3+l.callDepth, pcs[:])
  67. record := slog.NewRecord(time.Now(), level, msg, pcs[0])
  68. if l.name != "" {
  69. record.AddAttrs(slog.String(nameKey, l.name))
  70. }
  71. if err != nil {
  72. record.AddAttrs(slog.Any(errKey, err))
  73. }
  74. record.Add(kvList...)
  75. _ = l.handler.Handle(context.Background(), record)
  76. }
  77. func (l slogSink) WithName(name string) LogSink {
  78. if l.name != "" {
  79. l.name += "/"
  80. }
  81. l.name += name
  82. return &l
  83. }
  84. func (l slogSink) WithValues(kvList ...interface{}) LogSink {
  85. l.handler = l.handler.WithAttrs(kvListToAttrs(kvList...))
  86. return &l
  87. }
  88. func kvListToAttrs(kvList ...interface{}) []slog.Attr {
  89. // We don't need the record itself, only its Add method.
  90. record := slog.NewRecord(time.Time{}, 0, "", 0)
  91. record.Add(kvList...)
  92. attrs := make([]slog.Attr, 0, record.NumAttrs())
  93. record.Attrs(func(attr slog.Attr) bool {
  94. attrs = append(attrs, attr)
  95. return true
  96. })
  97. return attrs
  98. }