slog-handler.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package log
  2. import (
  3. "context"
  4. "log/slog"
  5. )
  6. type slogHandler struct {
  7. l Logger
  8. }
  9. func (s slogHandler) Enabled(ctx context.Context, level slog.Level) bool {
  10. // See IsEnabledFor for reasons why we probably should just return true here.
  11. return s.l.IsEnabledFor(fromSlogLevel(level))
  12. }
  13. func (s slogHandler) Handle(ctx context.Context, record slog.Record) error {
  14. s.l.LazyLog(fromSlogLevel(record.Level), func() Msg { return Msg{slogMsg{record}} })
  15. return nil
  16. }
  17. func (s slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
  18. //TODO implement me
  19. panic("implement me")
  20. }
  21. func (s slogHandler) WithGroup(name string) slog.Handler {
  22. //TODO implement me
  23. panic("implement me")
  24. }
  25. type slogMsg struct {
  26. record slog.Record
  27. }
  28. func (s slogMsg) Text() string {
  29. return s.record.Message
  30. }
  31. func (s slogMsg) Callers(skip int, pc []uintptr) int {
  32. if len(pc) >= 1 {
  33. pc[0] = s.record.PC
  34. return 1
  35. }
  36. return 0
  37. }
  38. func (s slogMsg) Values(callback valueIterCallback) {
  39. s.record.Attrs(func(attr slog.Attr) bool {
  40. return callback(item{attr.Key, attr.Value})
  41. })
  42. }