simplelog/simplelog.go

87 lines
1.9 KiB
Go

package simplelog
import (
"context"
"log"
"log/slog"
"os"
"github.com/mattn/go-isatty"
"github.com/mattn/go-isatty"
)
var (
relpServerURL = os.Getenv("LOGGER_RELP_URL")
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
func init() {
ourCustomLogger = NewCustomHandler()
slog.SetDefault(ourCustomLogger)
}
func NewCustomHandler() *CustomHandler {
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
}