Refactored CustomHandler to implement slog.Handler interface and updated initialization in init function.

This commit is contained in:
Jeffrey Paul 2024-05-14 05:20:43 -07:00
parent 500b4b0a96
commit 2c3d9a94fa
1 changed files with 38 additions and 42 deletions

View File

@ -7,8 +7,6 @@ import (
"os"
"github.com/mattn/go-isatty"
"github.com/mattn/go-isatty"
)
var (
@ -16,52 +14,20 @@ var (
webhookURL = os.Getenv("LOGGER_WEBHOOK_URL")
)
type CustomHandler struct {
handlers []slog.Handler
}
func (cl *CustomHandler) Handle(ctx context.Context, record slog.Record) error {
for _, handler := range cl.handlers {
if err := handler.Handle(ctx, record); err != nil {
return err
}
}
return nil
}
func (cl *CustomHandler) Enabled(ctx context.Context, level slog.Level) bool {
for _, handler := range cl.handlers {
if handler.Enabled(ctx, level) {
return true
}
}
return false
}
func (cl *CustomHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
newHandlers := make([]slog.Handler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithAttrs(attrs)
}
return &CustomHandler{handlers: newHandlers}
}
func (cl *CustomHandler) WithGroup(name string) slog.Handler {
newHandlers := make([]slog.Handler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithGroup(name)
}
return &CustomHandler{handlers: newHandlers}
}
var ourCustomLogger *slog.Logger
var ourCustomHandler slog.Handler
func init() {
ourCustomLogger = NewCustomHandler()
ourCustomHandler = NewCustomHandler()
ourCustomLogger = slog.New(ourCustomHandler)
slog.SetDefault(ourCustomLogger)
}
func NewCustomHandler() *CustomHandler {
type CustomHandler struct {
handlers []ExtendedHandler
}
func NewCustomHandler() slog.Handler {
cl := &CustomHandler{}
if isatty.IsTerminal(os.Stdout.Fd()) {
cl.handlers = append(cl.handlers, NewConsoleHandler())
@ -84,3 +50,33 @@ func NewCustomHandler() *CustomHandler {
}
return cl
}
func (cl *CustomHandler) Handle(ctx context.Context, record slog.Record) error {
for _, handler := range cl.handlers {
if err := handler.Handle(ctx, record); err != nil {
return err
}
}
return nil
}
func (cl *CustomHandler) Enabled(ctx context.Context, level slog.Level) bool {
// send us all events
return true
}
func (cl *CustomHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
newHandlers := make([]ExtendedHandler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithAttrs(attrs)
}
return &CustomHandler{handlers: newHandlers}
}
func (cl *CustomHandler) WithGroup(name string) slog.Handler {
newHandlers := make([]ExtendedHandler, len(cl.handlers))
for i, handler := range cl.handlers {
newHandlers[i] = handler.WithGroup(name)
}
return &CustomHandler{handlers: newHandlers}
}