Skip to content

Commit

Permalink
Update Logging handler (#238)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tang8330 authored Mar 7, 2024
1 parent cc71d3e commit e98415e
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 12 deletions.
22 changes: 18 additions & 4 deletions lib/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package logger
import (
"log/slog"
"os"
"time"

"github.com/getsentry/sentry-go"
"github.com/lmittmann/tint"
Expand All @@ -12,10 +13,11 @@ import (
"github.com/artie-labs/reader/config"
)

func NewLogger(settings *config.Settings) (*slog.Logger, bool) {
var handlersToTerminate []func()

func NewLogger(settings *config.Settings) (*slog.Logger, func()) {
handler := tint.NewHandler(os.Stderr, &tint.Options{Level: slog.LevelInfo})

var loggingToSentry bool
if settings != nil && settings.Reporting != nil && settings.Reporting.Sentry != nil && settings.Reporting.Sentry.DSN != "" {
if err := sentry.Init(sentry.ClientOptions{Dsn: settings.Reporting.Sentry.DSN}); err != nil {
slog.New(handler).Warn("Failed to enable Sentry output", slog.Any("err", err))
Expand All @@ -24,19 +26,31 @@ func NewLogger(settings *config.Settings) (*slog.Logger, bool) {
handler,
slogsentry.Option{Level: slog.LevelError}.NewSentryHandler(),
)
loggingToSentry = true

slog.New(handler).Info("Sentry logger enabled")
handlersToTerminate = append(handlersToTerminate, func() {
sentry.Flush(2 * time.Second)
})
}
}

return slog.New(handler), loggingToSentry
return slog.New(handler), runHandlers
}

func runHandlers() {
for _, handlerToTerminate := range handlersToTerminate {
handlerToTerminate()
}
}

func Fatal(msg string, args ...any) {
slog.Error(msg, args...)
runHandlers()
os.Exit(1)
}

func Panic(msg string, args ...any) {
slog.Error(msg, args...)
runHandlers()
panic(msg)
}
10 changes: 2 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ import (
"flag"
"fmt"
"log/slog"
"time"

"github.com/artie-labs/transfer/lib/telemetry/metrics"
"github.com/getsentry/sentry-go"

"github.com/artie-labs/reader/config"
"github.com/artie-labs/reader/lib/kafkalib"
Expand Down Expand Up @@ -72,13 +70,9 @@ func main() {
logger.Fatal("Failed to read config file", slog.Any("err", err))
}

_logger, usingSentry := logger.NewLogger(cfg)
_logger, cleanUpHandlers := logger.NewLogger(cfg)
defer cleanUpHandlers()
slog.SetDefault(_logger)
if usingSentry {
defer sentry.Flush(2 * time.Second)
slog.Info("Sentry logger enabled")
}

ctx := context.Background()

statsD, err := setUpMetrics(cfg.Metrics)
Expand Down

0 comments on commit e98415e

Please sign in to comment.