Skip to content

Commit

Permalink
replace gologger with slog (#356)
Browse files Browse the repository at this point in the history
  • Loading branch information
CubicrootXYZ authored Nov 23, 2024
1 parent 55c58cc commit baba29c
Show file tree
Hide file tree
Showing 78 changed files with 499 additions and 477 deletions.
9 changes: 6 additions & 3 deletions config.example.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# Enabel debug mode for verbose logging
debug: false

# Database settings
database:
# MySQL connection string
Expand Down Expand Up @@ -55,3 +52,9 @@ api:
apikey: xyz
# URL where the API can be reached (root level)
baseurl: https://example.com

# Logger settings
logger:
# Format must be one of: text, json
format: "text"
debug: false
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ module github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot
go 1.23

require (
github.com/CubicrootXYZ/gologger v0.4.0
github.com/CubicrootXYZ/gonaturalduration v0.6.0
github.com/CubicrootXYZ/gormlogger v0.0.0-20211030135540-f090b6c3590d
github.com/arran4/golang-ical v0.3.1
github.com/dchest/uniuri v1.2.0
github.com/gin-gonic/gin v1.10.0
github.com/golang/mock v1.6.0
github.com/jinzhu/configor v1.2.2
github.com/lmittmann/tint v1.0.5
github.com/stretchr/testify v1.9.0
github.com/teambition/rrule-go v1.8.2
github.com/tj/go-naturaldate v1.3.0
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4
github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/CubicrootXYZ/gologger v0.4.0 h1:P/QC3+KYG/9OLL7mv2lO5G6vo+gOCQQddHq3mib0qK8=
github.com/CubicrootXYZ/gologger v0.4.0/go.mod h1:ToO0WG8e9pFFg5JbwmT99PEJYrl0W6XlwMJ8Pzyf7Yc=
github.com/CubicrootXYZ/gonaturalduration v0.6.0 h1:EE+Aj5tsfx5NLb1kYLSTMc12ykGBKC5UnHULEx0TEM8=
github.com/CubicrootXYZ/gonaturalduration v0.6.0/go.mod h1:oQNxtz48TlkD0OIKRYfd+Fw4K7H7PndL6wbmoH51mX8=
github.com/CubicrootXYZ/gormlogger v0.0.0-20211030135540-f090b6c3590d h1:aeRXn89hSJJF9Ut/5FmkVwbgKW6VgnvaNseoB+uC+Ro=
Expand Down Expand Up @@ -71,6 +69,8 @@ github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/lmittmann/tint v1.0.5 h1:NQclAutOfYsqs2F1Lenue6OoWCajs5wJcP3DfWVpePw=
github.com/lmittmann/tint v1.0.5/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
Expand Down
4 changes: 2 additions & 2 deletions internal/api/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ func (server *server) assembleRoutes() error {
router := gin.New()

for name, provider := range server.config.RouteProviders {
server.logger.Infof("registering routes from: %s", name)
server.logger.Info("registering routes from provider", "provider", name)

err := provider.RegisterRoutes(router)
if err != nil {
server.logger.Errorf("error while setting up routes for '%s', routes might not be setup correctly: %v", name, err)
server.logger.Error("error while setting up routes for proider", "provider", name, "error", err)
continue
}
}
Expand Down
13 changes: 7 additions & 6 deletions internal/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@ package api

import (
"errors"
"log/slog"
"net/http"
"time"

"github.com/CubicrootXYZ/gologger"
"github.com/gin-gonic/gin"
"golang.org/x/net/context"
)

type server struct {
server *http.Server
config *Config
logger gologger.Logger
logger *slog.Logger
}

type RouteProvider interface {
Expand All @@ -27,7 +27,7 @@ type Config struct {
}

// NewServer assembles a new API webserver.
func NewServer(config *Config, logger gologger.Logger) Server {
func NewServer(config *Config, logger *slog.Logger) Server {
return &server{
config: config,
logger: logger,
Expand All @@ -37,7 +37,7 @@ func NewServer(config *Config, logger gologger.Logger) Server {
// Start the webserver and serve the given endpoints.
// Blocks until stopped.
func (server *server) Start() error {
server.logger.Infof("starting server at '%s'", server.config.Address)
server.logger.Info("starting server", "address", server.config.Address)
err := server.assembleRoutes()
if err != nil {
return err
Expand All @@ -56,8 +56,9 @@ func (server *server) Start() error {
// Stop the server.
// Might take a few moments.
func (server *server) Stop() error {
server.logger.Infof("stopping server ...")
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
timeout := time.Second * 5
server.logger.Info("stopping server", "timeout", timeout)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return server.server.Shutdown(ctx)
}
44 changes: 38 additions & 6 deletions internal/cmd/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,35 @@ package cmd
import (
"errors"
"flag"
"log/slog"
"os"
"slices"
"time"

"github.com/CubicrootXYZ/gologger"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/api"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/daemon"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database"
"github.com/jinzhu/configor"
"github.com/lmittmann/tint"
)

type Config struct {
Debug bool
Database configDatabase
Daemon configDaemon
Matrix configMatrix
ICal configICal
API configAPI
Logger configLogger

BuildVersion string
}

type configLogger struct {
Format string `default:"text"`
Debug bool
}

type configDatabase struct {
Connection string `required:"true"`
LogStatements bool
Expand Down Expand Up @@ -67,12 +75,32 @@ func (config *Config) databaseConfig() *database.Config {
}
}

func (config *Config) loggerConfig() gologger.LogLevel {
if config.Debug {
return gologger.LogLevelDebug
func (config *Config) logger() *slog.Logger {
logLevel := slog.LevelInfo
if config.Logger.Debug {
logLevel = slog.LevelDebug
}

var handler slog.Handler
switch config.Logger.Format {
case "text":
handler = tint.NewHandler(os.Stdout, &tint.Options{
AddSource: true,
Level: logLevel,
TimeFormat: time.RFC3339Nano,
})
case "json":
handler = slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
AddSource: true,
Level: logLevel,
})
default:
handler = slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
Level: logLevel,
})
}

return gologger.LogLevelInfo
return slog.New(handler)
}

func (config *Config) daemonConfig() *daemon.Config {
Expand Down Expand Up @@ -121,5 +149,9 @@ func LoadConfiguration() (*Config, error) {
return nil, errors.New("API key needs to be at least 10 characters")
}

if !slices.Contains([]string{"text", "json"}, config.Logger.Format) {
return nil, errors.New("logger format must be one of: text, json")
}

return config, nil
}
45 changes: 22 additions & 23 deletions internal/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ package cmd

import (
"context"
"log/slog"
"net/url"
"os"
"os/signal"
"syscall"
"time"

"github.com/CubicrootXYZ/gologger"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/api"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/api/middleware"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical"
Expand All @@ -28,13 +28,12 @@ import (

// Run setups the application and runs it
func Run(config *Config) error {
logger := gologger.New(config.loggerConfig(), 0).WithField("component", "cmd")
defer logger.Flush()
logger := config.logger()

logger.Infof("starting up RemindMe with version '%s' ...", config.BuildVersion)
logger.Info("starting up RemindMe", "version", config.BuildVersion)
processes, err := setup(config, logger)
if err != nil {
logger.Err(err)
logger.Error("startup failed", "error", err)
return err
}

Expand All @@ -46,15 +45,15 @@ func Run(config *Config) error {
go func() {
select {
case s := <-sigChan:
logger.Infof("received signal, shutting down: %v", s)
logger.Info("shutting down", "reason", "signal", "signal", s)
case <-ctx.Done():
logger.Infof("at least one process exited, shutting down")
logger.Info("shutting down", "reason", "process exited")
}

for _, p := range processes {
err := p.Stop()
if err != nil {
logger.Err(err)
logger.Error("process stopped with error", "error", err)
}
}
}()
Expand All @@ -67,10 +66,10 @@ func Run(config *Config) error {

err = eg.Wait()
if err != nil {
logger.Err(err)
logger.Error("error group stopped with error", "error", err)
}

logger.Infof("shut down complete, bye")
logger.Info("shut down complete, bye")
return err
}

Expand All @@ -79,7 +78,7 @@ type process interface {
Stop() error
}

func setup(config *Config, logger gologger.Logger) ([]process, error) {
func setup(config *Config, logger *slog.Logger) ([]process, error) {
baseURL, err := url.Parse(config.API.BaseURL)
if err != nil {
return nil, err
Expand All @@ -90,24 +89,24 @@ func setup(config *Config, logger gologger.Logger) ([]process, error) {
dbConfig := config.databaseConfig()
dbConfig.InputServices = make(map[string]database.InputService)
dbConfig.OutputServices = make(map[string]database.OutputService)
db, err := database.NewService(dbConfig, logger.WithField("component", "database"))
db, err := database.NewService(dbConfig, logger.With("component", "database"))
if err != nil {
logger.Err(err)
logger.Error("failed to assemble database service", "error", err)
return nil, err
}

// iCal connector
icalDB, err := icaldb.New(db.GormDB())
if err != nil {
logger.Err(err)
logger.Error("failed to assemble iCal database service", "error", err)
return nil, err
}
icalConnector := ical.New(&ical.Config{
ICalDB: icalDB,
Database: db,
BaseURL: baseURL,
RefreshInterval: time.Minute * time.Duration(config.ICal.RefreshInterval),
}, logger.WithField("component", "ical connector"))
}, logger.With("component", "ical connector"))

dbConfig.OutputServices[ical.OutputType] = icalConnector
dbConfig.OutputServices[ical.InputType] = icalConnector
Expand All @@ -116,13 +115,13 @@ func setup(config *Config, logger gologger.Logger) ([]process, error) {
// Matrix connector
matrixDB, err := matrixdb.New(db.GormDB())
if err != nil {
logger.Err(err)
logger.Error("failed to assemble matrix database service", "error", err)
return nil, err
}

matrixConnector, err := matrix.New(assembleMatrixConfig(config, icalConnector), db, matrixDB, logger.WithField("component", "matrix connector"))
matrixConnector, err := matrix.New(assembleMatrixConfig(config, icalConnector), db, matrixDB, logger.With("component", "matrix connector"))
if err != nil {
logger.Err(err)
logger.Error("failed to assemble matrix connector service", "error", err)
return nil, err
}
processes = append(processes, matrixConnector)
Expand All @@ -135,7 +134,7 @@ func setup(config *Config, logger gologger.Logger) ([]process, error) {
daemonConf.OutputServices = make(map[string]daemon.OutputService)
daemonConf.OutputServices[matrix.OutputType] = matrixConnector
daemonConf.OutputServices[ical.OutputType] = icalConnector
daemon := daemon.New(daemonConf, db, logger.WithField("component", "daemon"))
daemon := daemon.New(daemonConf, db, logger.With("component", "daemon"))
processes = append(processes, daemon)

// API
Expand All @@ -144,26 +143,26 @@ func setup(config *Config, logger gologger.Logger) ([]process, error) {
coreAPI := coreapi.New(&coreapi.Config{
Database: db,
DefaultAuthProvider: middleware.APIKeyAuth(config.API.APIKey),
}, logger.WithField("component", "core API"))
}, logger.With("component", "core API"))

// Matrix API
matrixAPI := matrixapi.New(&matrixapi.Config{
Database: db,
MatrixDB: matrixDB,
DefaultAuthProvider: middleware.APIKeyAuth(config.API.APIKey),
}, logger.WithField("component", "matrix API"))
}, logger.With("component", "matrix API"))

// iCal API
icalAPI := icalapi.New(&icalapi.Config{
IcalDB: icalDB,
Database: db,
}, logger.WithField("component", "ical API"))
}, logger.With("component", "ical API"))

apiConfig := config.apiConfig()
apiConfig.RouteProviders["core"] = coreAPI
apiConfig.RouteProviders["matrix"] = matrixAPI
apiConfig.RouteProviders["ical"] = icalAPI
server := api.NewServer(apiConfig, logger.WithField("component", "api"))
server := api.NewServer(apiConfig, logger.With("component", "api"))
processes = append(processes, server)
}

Expand Down
7 changes: 4 additions & 3 deletions internal/connectors/ical/api/api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package api

import (
"github.com/CubicrootXYZ/gologger"
"log/slog"

"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/api/apictx"
icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database"
"github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database"
Expand All @@ -17,11 +18,11 @@ type Config struct {
type api struct {
icalDB icaldb.Service
database database.Service
logger gologger.Logger
logger *slog.Logger
}

// New assembles a new iCal API.
func New(config *Config, logger gologger.Logger) API {
func New(config *Config, logger *slog.Logger) API {
return &api{
icalDB: config.IcalDB,
logger: logger,
Expand Down
Loading

0 comments on commit baba29c

Please sign in to comment.