package simplelog import ( "context" "log" "log/slog" "os" "github.com/mattn/go-isatty" ) var ( relpServerURL = os.Getenv("LOGGER_RELP_URL") webhookURL = os.Getenv("LOGGER_WEBHOOK_URL") ) var ourCustomLogger *slog.Logger var ourCustomHandler slog.Handler func init() { ourCustomHandler = NewCustomHandler() ourCustomLogger = slog.New(ourCustomHandler) slog.SetDefault(ourCustomLogger) } type CustomHandler struct { handlers []ExtendedHandler } func NewCustomHandler() slog.Handler { cl := &CustomHandler{} if isatty.IsTerminal(os.Stdout.Fd()) { cl.handlers = append(cl.handlers, NewConsoleHandler()) } else { cl.handlers = append(cl.handlers, NewJSONHandler()) } if relpServerURL != "" { handler, err := NewRELPHandler(relpServerURL) if err != nil { log.Fatalf("Failed to initialize RELP handler: %v", err) } cl.handlers = append(cl.handlers, handler) } if webhookURL != "" { handler, err := NewWebhookHandler(webhookURL) if err != nil { log.Fatalf("Failed to initialize Webhook handler: %v", err) } cl.handlers = append(cl.handlers, handler) } 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} }