github.com/sujit-baniya/log@v1.0.73/slog_handler.go (about) 1 package log 2 3 import ( 4 "context" 5 "log/slog" 6 ) 7 8 type slogHandler struct { 9 Logger 10 } 11 12 func (h *slogHandler) Enabled(_ context.Context, level slog.Level) bool { 13 switch level { 14 case slog.LevelDebug: 15 return h.Logger.Level <= DebugLevel 16 case slog.LevelInfo: 17 return h.Logger.Level <= InfoLevel 18 case slog.LevelWarn: 19 return h.Logger.Level <= WarnLevel 20 case slog.LevelError: 21 return h.Logger.Level <= ErrorLevel 22 } 23 return false 24 } 25 26 func (h *slogHandler) Handle(_ context.Context, r slog.Record) error { 27 e := h.Logger.Log() 28 r.Attrs(func(attr slog.Attr) bool { 29 e = e.Any(attr.Key, attr.Value) 30 return true 31 }) 32 e.Msg(r.Message) 33 return nil 34 } 35 36 func (h *slogHandler) WithAttrs(attrs []slog.Attr) slog.Handler { 37 e := NewContext(nil) 38 for _, attr := range attrs { 39 e = e.Any(attr.Key, attr.Value) 40 } 41 42 l := h.Logger 43 l.Context = e.Value() 44 45 return &slogHandler{l} 46 } 47 48 func (h *slogHandler) WithGroup(name string) slog.Handler { 49 return h 50 } 51 52 // Slog wraps the Logger to provide *slog.Logger 53 func (l *Logger) Slog() *slog.Logger { 54 return slog.New(&slogHandler{*l}) 55 }