From 373dd0ac76c48ee50add9a94e2886261d7a46b67 Mon Sep 17 00:00:00 2001 From: sneak Date: Tue, 14 May 2024 04:48:28 -0700 Subject: [PATCH] Add custom logger with different handlers based on environment variables. --- simplelog.go | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 simplelog.go diff --git a/simplelog.go b/simplelog.go new file mode 100644 index 0000000..9843e96 --- /dev/null +++ b/simplelog.go @@ -0,0 +1,58 @@ +package simplelog + +import ( + "log" + "log/slog" + "os" + + "github.com/mattn/go-isatty" +) + +var ( + relpServerURL = os.Getenv("LOGGER_RELP_URL") + webhookURL = os.Getenv("LOGGER_WEBHOOK_URL") +) + +type CustomLogger struct { + handlers []slog.Handler +} + +func (cl *CustomLogger) Log(level slog.Level, message string, data ...slog.Field) error { + for _, handler := range cl.handlers { + if err := handler.Log(level, message, data...); err != nil { + return err + } + } + return nil +} + +var ourCustomLogger *slog.Logger + +func init() { + ourCustomLogger = NewCustomLogger() + slog.SetDefault(ourCustomLogger) +} + +func NewCustomLogger() *CustomLogger { + cl := &CustomLogger{} + 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 +}