Skip to content

Commit

Permalink
logger: replace zap with slog
Browse files Browse the repository at this point in the history
  • Loading branch information
alessio-perugini committed Oct 20, 2024
1 parent c87e819 commit 6ea7d83
Show file tree
Hide file tree
Showing 8 changed files with 43 additions and 70 deletions.
45 changes: 18 additions & 27 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"os/signal"
Expand All @@ -13,7 +14,6 @@ import (
"time"

_ "github.com/tursodatabase/libsql-client-go/libsql"
"go.uber.org/zap"

"github.com/alessio-perugini/f1calendarbot/pkg/f1calendar"
"github.com/alessio-perugini/f1calendarbot/pkg/metrics"
Expand All @@ -26,75 +26,66 @@ import (
const f1CalendarEndpoint = "https://raw.githubusercontent.com/sportstimes/f1/main/_db/f1/2024.json"

func main() {
logger, err := zap.NewProduction()
if err != nil {
panic(err)
}
defer func() {
_ = logger.Sync()
}()

if buildInfo, ok := debug.ReadBuildInfo(); ok {
logger.Info("f1calendar ", zap.String("buildinfo", buildInfo.String()))
slog.Info("f1calendar ", slog.String("buildinfo", buildInfo.String()))
}

tkn := os.Getenv("F1CALENDAR__TELEGRAM_TOKEN")
if tkn == "" {
logger.Fatal("no valid telegram token provided")
panic("no valid telegram token provided")
}
dbURL := os.Getenv("F1CALENDAR__DATABASE_URL")
dbAuthToken := os.Getenv("F1CALENDAR__TURSO_AUTH_TOKEN")

db, err := sql.Open("libsql", fmt.Sprintf("libsql://%s.turso.io?authToken=%s", dbURL, dbAuthToken))
if err != nil {
logger.Fatal(fmt.Errorf("unable to connect to database: %v", err).Error())
panic(fmt.Errorf("unable to connect to database: %v", err).Error())
}
defer db.Close()

healthServer := healthCheckServer(db, logger)
healthServer := healthCheckServer(db)
go func() {
if err := healthServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error(err.Error())
slog.Error(err.Error())
}
}()
defer func() {
if err := healthServer.Shutdown(context.Background()); err != nil {
logger.Error(err.Error())
slog.Error(err.Error())
}
}()

metricsServer := metrics.NewServer(logger)
metricsServer := metrics.NewServer()
go func() {
if err := metricsServer.ListenAndServe(":9000"); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error(err.Error())
slog.Error(err.Error())
}
}()
defer func() {
if err := metricsServer.Shutdown(context.Background()); err != nil {
logger.Error(err.Error())
slog.Error(err.Error())
}
}()

tb, err := telegram.NewTelegramRepository(tkn, logger)
tb, err := telegram.NewTelegramRepository(tkn)
if err != nil {
logger.Fatal(err.Error())
panic(err.Error())
}

cachedRaceWeekFetcher := f1calendar.NewCachedRaceWeek(f1calendar.NewCalendarFetcher(f1CalendarEndpoint, logger))
subscriptionService := subscription.NewSubscriptionService(store.NewSubscriptionStore(db), logger)
cachedRaceWeekFetcher := f1calendar.NewCachedRaceWeek(f1calendar.NewCalendarFetcher(f1CalendarEndpoint))
subscriptionService := subscription.NewSubscriptionService(store.NewSubscriptionStore(db))
h := handler.NewHandler(tb, subscriptionService, cachedRaceWeekFetcher)

// load handlers
tb.LoadHandler("/subscribe", h.OnSubscribe)
tb.LoadHandler("/unsubscribe", h.OnUnsubscribe)
tb.LoadHandler("/nextrace", h.OnRaceWeek)

logger.Info("Server is starting...")
slog.Info("Server is starting...")

engine := f1calendar.NewEngine(
cachedRaceWeekFetcher,
f1calendar.NewAlert(f1calendar.SendTelegramAlert(tb, subscriptionService)),
logger,
)
go engine.Start()
go tb.Start()
Expand All @@ -103,17 +94,17 @@ func main() {
signal.Notify(signalCh, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP)

<-signalCh
logger.Info("Server is stopping...")
slog.Info("Server is stopping...")

engine.Stop()
tb.Stop()
}

func healthCheckServer(db *sql.DB, logger *zap.Logger) *http.Server {
func healthCheckServer(db *sql.DB) *http.Server {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
if err := db.Ping(); err != nil {
logger.Error("healthcheck error", zap.Error(err))
slog.Error("healthcheck error", slog.Any("err", err))
w.WriteHeader(http.StatusInternalServerError)
return
}
Expand Down
2 changes: 0 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ require (
github.com/prometheus/client_golang v1.20.5
github.com/shoenig/test v1.11.0
github.com/tursodatabase/libsql-client-go v0.0.0-20240812094001-348a4e45b535
go.uber.org/zap v1.27.0
gopkg.in/telebot.v3 v3.3.8
)

Expand All @@ -24,7 +23,6 @@ require (
github.com/prometheus/common v0.57.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 // indirect
golang.org/x/sys v0.24.0 // indirect
google.golang.org/protobuf v1.34.2 // indirect
Expand Down
6 changes: 0 additions & 6 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -409,14 +409,8 @@ go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk=
go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E=
go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU=
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
go.uber.org/zap v1.17.0/go.mod h1:MXVU+bhUf/A7Xi2HNOnopQOrmycQ5Ih87HtOu4q5SSo=
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
Expand Down
12 changes: 5 additions & 7 deletions pkg/f1calendar/calendar_fetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,19 @@ import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"sort"
"time"

"go.uber.org/zap"
)

type CalendarFetcher struct {
client *http.Client
endpointURL string
logger *zap.Logger
}

func NewCalendarFetcher(endpointURL string, logger *zap.Logger) *CalendarFetcher {
return &CalendarFetcher{client: &http.Client{}, endpointURL: endpointURL, logger: logger}
func NewCalendarFetcher(endpointURL string) *CalendarFetcher {
return &CalendarFetcher{client: &http.Client{}, endpointURL: endpointURL}
}

func (c CalendarFetcher) getF1Calendar() *F1Calendar {
Expand All @@ -31,13 +29,13 @@ func (c CalendarFetcher) getF1Calendar() *F1Calendar {

body, err := io.ReadAll(r.Body)
if err != nil {
c.logger.Error(err.Error())
slog.Error(err.Error())
return nil
}

var calendar F1Calendar
if err = json.Unmarshal(body, &calendar); err != nil {
c.logger.Error(err.Error())
slog.Error(err.Error())
return nil
}

Expand Down
13 changes: 5 additions & 8 deletions pkg/f1calendar/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,21 @@ package f1calendar
import (
"context"
"fmt"
"log/slog"
"time"

"go.uber.org/zap"
)

type Engine struct {
raceWeekRepository RaceWeekRepository
alertService *Alert
stop chan struct{}
logger *zap.Logger
}

func NewEngine(raceWeekRepository RaceWeekRepository, alertService *Alert, logger *zap.Logger) *Engine {
func NewEngine(raceWeekRepository RaceWeekRepository, alertService *Alert) *Engine {
return &Engine{
raceWeekRepository: raceWeekRepository,
alertService: alertService,
stop: make(chan struct{}),
logger: logger,
}
}

Expand All @@ -32,7 +29,7 @@ func (e *Engine) Start() {
for {
select {
case now := <-ticker.C:
e.logger.Debug("checking for new f1 calendar events")
slog.Debug("checking for new f1 calendar events")

// f1 events starts on friday, this is used to not waste resources
if now.Weekday() == time.Sunday || now.Weekday() >= time.Thursday {
Expand All @@ -48,10 +45,10 @@ func (e *Engine) Start() {
func (e *Engine) prepareNotificationTriggers() {
calendar := e.raceWeekRepository.GetRaceWeek()
if calendar == nil {
e.logger.Info("No race available")
slog.Info("No race available")
return
}
e.logger.Info(fmt.Sprintf("next f1 events is %s", calendar.Location))
slog.Info(fmt.Sprintf("next f1 events is %s", calendar.Location))

nextSession := calendar.Sessions[0]

Expand Down
9 changes: 4 additions & 5 deletions pkg/metrics/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package metrics
import (
"context"
"errors"
"log/slog"
"net/http"
"time"

"github.com/prometheus/client_golang/prometheus/promhttp"
"go.uber.org/zap"
)

var (
Expand All @@ -17,11 +17,10 @@ var (
type Server struct {
srv *http.Server
handler http.Handler
logger *zap.Logger
}

func (s *Server) ListenAndServe(addr string) error {
s.logger.Info("metrics: listening on %s")
slog.Info("metrics: listening on %s")

s.srv = &http.Server{
Addr: addr,
Expand All @@ -48,9 +47,9 @@ func (s *Server) Shutdown(ctx context.Context) error {
return s.srv.Shutdown(ctx)
}

func NewServer(logger *zap.Logger) *Server {
func NewServer() *Server {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())

return &Server{handler: mux, logger: logger}
return &Server{handler: mux}
}
15 changes: 6 additions & 9 deletions pkg/subscription/subscription.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package subscription

import (
"go.uber.org/zap"
"log/slog"

"github.com/alessio-perugini/f1calendarbot/pkg/subscription/store"
)
Expand All @@ -13,36 +13,33 @@ type Service interface {
}

type Subscription struct {
store *store.SubscriptionStore
logger *zap.Logger
store *store.SubscriptionStore
}

func NewSubscriptionService(
subscriptionStore *store.SubscriptionStore,
logger *zap.Logger,
) *Subscription {
return &Subscription{
store: subscriptionStore,
logger: logger,
store: subscriptionStore,
}
}

func (s *Subscription) Subscribe(id int64) {
if err := s.store.Subscribe(id); err != nil {
s.logger.Error("unable to subscribe", zap.Error(err))
slog.Error("unable to subscribe", slog.Any("err", err))
}
}

func (s *Subscription) Unsubscribe(id int64) {
if err := s.store.Unsubscribe(id); err != nil {
s.logger.Error("unable to unsubscribe", zap.Error(err))
slog.Error("unable to unsubscribe", slog.Any("err", err))
}
}

func (s *Subscription) GetAllSubscribedChats() []int64 {
res, err := s.store.GetAllSubscribedChats()
if err != nil {
s.logger.Error("unable to retrieve all subscribed chats", zap.Error(err))
slog.Error("unable to retrieve all subscribed chats", slog.Any("err", err))
}
return res
}
11 changes: 5 additions & 6 deletions pkg/telegram/telegram.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
package telegram

import (
"log/slog"
"time"

"github.com/prometheus/client_golang/prometheus"
"go.uber.org/zap"
tb "gopkg.in/telebot.v3"
)

Expand All @@ -16,8 +16,7 @@ type Repository interface {
}

type telegram struct {
tBot *tb.Bot
logger *zap.Logger
tBot *tb.Bot
}

var (
Expand All @@ -30,20 +29,20 @@ var (
)
)

func NewTelegramRepository(tkn string, logger *zap.Logger) (Repository, error) {
func NewTelegramRepository(tkn string) (Repository, error) {
prometheus.MustRegister(requestDurationSummary)
tBot, err := tb.NewBot(tb.Settings{
Token: tkn,
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
OnError: func(err error, c tb.Context) {
logger.Error(err.Error(), zap.String("sender", c.Sender().Recipient()))
slog.Error(err.Error(), slog.String("sender", c.Sender().Recipient()))
},
})
if err != nil {
return nil, err
}

return &telegram{tBot: tBot, logger: logger}, nil
return &telegram{tBot: tBot}, nil
}

func (t telegram) LoadHandler(endpoint string, handler tb.HandlerFunc) {
Expand Down

0 comments on commit 6ea7d83

Please sign in to comment.