diff --git a/config.example.yml b/config.example.yml index 45e4fcf9..44e3fc8f 100644 --- a/config.example.yml +++ b/config.example.yml @@ -1,6 +1,3 @@ -# Enabel debug mode for verbose logging -debug: false - # Database settings database: # MySQL connection string @@ -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 \ No newline at end of file diff --git a/go.mod b/go.mod index 7da49802..7b145b79 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ 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 @@ -11,6 +10,7 @@ require ( 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 diff --git a/go.sum b/go.sum index 2a450046..dad6cb9d 100644 --- a/go.sum +++ b/go.sum @@ -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= @@ -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= diff --git a/internal/api/routes.go b/internal/api/routes.go index a383add5..215b1d3b 100644 --- a/internal/api/routes.go +++ b/internal/api/routes.go @@ -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 } } diff --git a/internal/api/server.go b/internal/api/server.go index 86511913..cc85e08e 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -2,10 +2,10 @@ package api import ( "errors" + "log/slog" "net/http" "time" - "github.com/CubicrootXYZ/gologger" "github.com/gin-gonic/gin" "golang.org/x/net/context" ) @@ -13,7 +13,7 @@ import ( type server struct { server *http.Server config *Config - logger gologger.Logger + logger *slog.Logger } type RouteProvider interface { @@ -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, @@ -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 @@ -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) } diff --git a/internal/cmd/configuration.go b/internal/cmd/configuration.go index a2a00210..87dda64a 100644 --- a/internal/cmd/configuration.go +++ b/internal/cmd/configuration.go @@ -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 @@ -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 { @@ -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 } diff --git a/internal/cmd/run.go b/internal/cmd/run.go index 9845c010..a5da1382 100644 --- a/internal/cmd/run.go +++ b/internal/cmd/run.go @@ -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" @@ -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 } @@ -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) } } }() @@ -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 } @@ -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 @@ -90,16 +89,16 @@ 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{ @@ -107,7 +106,7 @@ func setup(config *Config, logger gologger.Logger) ([]process, error) { 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 @@ -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) @@ -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 @@ -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) } diff --git a/internal/connectors/ical/api/api.go b/internal/connectors/ical/api/api.go index e7da56ee..425545a8 100644 --- a/internal/connectors/ical/api/api.go +++ b/internal/connectors/ical/api/api.go @@ -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" @@ -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, diff --git a/internal/connectors/ical/api/api_test.go b/internal/connectors/ical/api/api_test.go index 45a7832b..0eb627c8 100644 --- a/internal/connectors/ical/api/api_test.go +++ b/internal/connectors/ical/api/api_test.go @@ -1,9 +1,9 @@ package api_test import ( + "log/slog" "net/http/httptest" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/api" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -18,7 +18,7 @@ func testServer(ctrl *gomock.Controller) (*database.MockService, *icaldb.MockSer api := api.New(&api.Config{ Database: db, IcalDB: icalDB, - }, gologger.New(gologger.LogLevelDebug, 0)) + }, slog.Default()) r := gin.New() err := api.RegisterRoutes(r) diff --git a/internal/connectors/ical/api/ical.go b/internal/connectors/ical/api/ical.go index f56a572d..d97d4011 100644 --- a/internal/connectors/ical/api/ical.go +++ b/internal/connectors/ical/api/ical.go @@ -47,7 +47,7 @@ func (api *api) icalExportHandler(ctx *gin.Context) { response.AbortWithNotFoundError(ctx) return } - api.logger.Err(err) + api.logger.Error("failed to get iCal output", "error", err, "ical.output.id", id) response.AbortWithInternalServerError(ctx) return } @@ -63,14 +63,14 @@ func (api *api) icalExportHandler(ctx *gin.Context) { response.AbortWithNotFoundError(ctx) return } - api.logger.Err(err) + api.logger.Error("failed to get output from database", "error", err) response.AbortWithInternalServerError(ctx) return } events, err := api.database.GetEventsByChannel(o.ChannelID) if err != nil { - api.logger.Err(err) + api.logger.Error("failed to get events from database", "error", err) response.AbortWithInternalServerError(ctx) return } diff --git a/internal/connectors/ical/database/service_test.go b/internal/connectors/ical/database/service_test.go index 0f2827d6..15c4b6b3 100644 --- a/internal/connectors/ical/database/service_test.go +++ b/internal/connectors/ical/database/service_test.go @@ -4,13 +4,11 @@ import ( "os" "testing" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "gorm.io/driver/mysql" "gorm.io/gorm" ) -var logger gologger.Logger var service database.Service var gormDB *gorm.DB @@ -41,12 +39,7 @@ func getService(gormDB *gorm.DB) database.Service { return service } -func getLogger() gologger.Logger { - return gologger.New(gologger.LogLevelDebug, 0) -} - func TestMain(m *testing.M) { - logger = getLogger() gormDB = getGormDB() service = getService(gormDB) diff --git a/internal/connectors/ical/fetcher.go b/internal/connectors/ical/fetcher.go index adedf96d..c2f8275e 100644 --- a/internal/connectors/ical/fetcher.go +++ b/internal/connectors/ical/fetcher.go @@ -5,11 +5,11 @@ import ( "errors" "fmt" "io" + "log/slog" "net/http" "strconv" "time" - "github.com/CubicrootXYZ/gologger" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/format" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -20,31 +20,31 @@ const ( ) func (service *service) refreshIcalInputs() { - service.logger.Debugf("refreshing iCal inputs now ...") + service.logger.Debug("refreshing iCal inputs") f := false inputs, err := service.config.ICalDB.ListIcalInputs(&icaldb.ListIcalInputsOpts{ Disabled: &f, }) if err != nil { - service.logger.Err(err) + service.logger.Error("failed to list iCal inputs", "error", err) return } for _, input := range inputs { - l := service.logger.WithField("iCal input ID", input.ID) + l := service.logger.With("ical.input_id", input.ID) if input.LastRefresh != nil && time.Since(*input.LastRefresh) < service.config.RefreshInterval { - l.Debugf("skipping input as has not yet reached the refresh interval") + l.Debug("skipping input as has not yet reached the refresh interval") continue } now := time.Now() err := service.refreshIcalInput(&input) if err != nil { - l.Infof("failed refreshing: %v", input.ID, err) + l.Info("failed refreshing input", "error", err) if input.LastRefresh != nil && time.Since(*input.LastRefresh) > time.Hour*48 { - l.Infof("disabling input, no success refrehsing since 48 hours") + l.Info("disabling input, no successful refresh in 48 hours") input.Disabled = true } } else { @@ -54,7 +54,7 @@ func (service *service) refreshIcalInputs() { _, err = service.config.ICalDB.UpdateIcalInput(&input) if err != nil { - l.Infof("failed updating input in database: %v", err) + l.Info("failed updating input in database", "error", err) continue } } @@ -128,7 +128,7 @@ func (service *service) refreshIcalInput(input *icaldb.IcalInput) error { return nil } -func getFileContent(url string, logger gologger.Logger) (string, error) { +func getFileContent(url string, logger *slog.Logger) (string, error) { ctx, cancel := context.WithTimeout(context.Background(), time.Second*15) defer cancel() @@ -137,7 +137,7 @@ func getFileContent(url string, logger gologger.Logger) (string, error) { return "", err } req.Header.Set("Accept", "text/calendar") - logger.Debugf("making request with GET to %s", url) + logger.Debug("making request", "url", url, "http.method", "GET") client := &http.Client{} resp, err := client.Do(req) diff --git a/internal/connectors/ical/service.go b/internal/connectors/ical/service.go index 2a577164..48bde9ad 100644 --- a/internal/connectors/ical/service.go +++ b/internal/connectors/ical/service.go @@ -3,10 +3,10 @@ package ical import ( "errors" "fmt" + "log/slog" "net/url" "time" - "github.com/CubicrootXYZ/gologger" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/daemon" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -28,13 +28,13 @@ type Config struct { type service struct { config *Config - logger gologger.Logger + logger *slog.Logger stop chan bool } // New assembles a new ical connector service. -func New(config *Config, logger gologger.Logger) Service { +func New(config *Config, logger *slog.Logger) Service { return &service{ config: config, logger: logger, @@ -58,7 +58,7 @@ func (service *service) Start() error { func (service *service) Stop() error { service.stop <- true - service.logger.Infof("stopping") + service.logger.Info("stopping") return nil } diff --git a/internal/connectors/ical/service_test.go b/internal/connectors/ical/service_test.go index e92065c0..10259430 100644 --- a/internal/connectors/ical/service_test.go +++ b/internal/connectors/ical/service_test.go @@ -2,6 +2,7 @@ package ical_test import ( "errors" + "log/slog" "net/http" "net/http/httptest" "net/url" @@ -9,7 +10,6 @@ import ( "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -27,7 +27,7 @@ func testService(ctrl *gomock.Controller) (ical.Service, *icaldb.MockService, *d Database: db, ICalDB: icalDB, BaseURL: url, - }, gologger.New(gologger.LogLevelDebug, 0)), + }, slog.New(slog.NewTextHandler(os.Stdout, nil))), icalDB, db } diff --git a/internal/connectors/matrix/actions/message/_action.go.example b/internal/connectors/matrix/actions/message/_action.go.example index 8a247c4e..da0c66da 100644 --- a/internal/connectors/matrix/actions/message/_action.go.example +++ b/internal/connectors/matrix/actions/message/_action.go.example @@ -1,10 +1,10 @@ package message import ( + "log/slog" "regexp" "strings" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -17,7 +17,7 @@ var exampleActionRegex = regexp.MustCompile("(?i)example .*") // ExampleAction acts as a template for new actions. type ExampleAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -25,7 +25,7 @@ type ExampleAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ExampleAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ExampleAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -52,5 +52,5 @@ func (action *ExampleAction) Selector() *regexp.Regexp { // HandleEvent is where the message event get's send to if it matches the Selector. func (action *ExampleAction) HandleEvent(event *matrix.MessageEvent) { - action.logger.Infof("Example action called") + action.logger.Info("Example action called") } diff --git a/internal/connectors/matrix/actions/message/add_user.go b/internal/connectors/matrix/actions/message/add_user.go index 5c08fecd..837c58ee 100644 --- a/internal/connectors/matrix/actions/message/add_user.go +++ b/internal/connectors/matrix/actions/message/add_user.go @@ -1,10 +1,10 @@ package message import ( + "log/slog" "regexp" "strings" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -17,14 +17,14 @@ import ( var addUserActionRegex = regexp.MustCompile("(?i)(^[ ]*add[ ]+user).*") type AddUserAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service db database.Service } -func (action *AddUserAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *AddUserAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -49,7 +49,7 @@ func (action *AddUserAction) Selector() *regexp.Regexp { func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { usersInRoom, err := action.client.JoinedMembers(event.Event.RoomID) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to get room members", "error", err) return } @@ -72,7 +72,7 @@ func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } @@ -105,7 +105,7 @@ func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } @@ -121,7 +121,7 @@ func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } @@ -130,7 +130,7 @@ func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { // Add new user to room _, err = action.matrixDB.AddUserToRoom(username, event.Room) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to add user to room", "error", err) return } @@ -139,7 +139,7 @@ func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { msg.Type = matrixdb.MessageTypeAddUser _, err = action.matrixDB.NewMessage(msg) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to store messafe to database", "error", err) } message := "Added that user 👏. They can now interact with me." @@ -151,7 +151,7 @@ func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) return } @@ -164,6 +164,6 @@ func (action *AddUserAction) HandleEvent(event *matrix.MessageEvent) { msg.BodyFormatted = message _, err = action.matrixDB.NewMessage(msg) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to store response to database", "error", err) } } diff --git a/internal/connectors/matrix/actions/message/add_user_test.go b/internal/connectors/matrix/actions/message/add_user_test.go index 0a293fa6..f89c06fb 100644 --- a/internal/connectors/matrix/actions/message/add_user_test.go +++ b/internal/connectors/matrix/actions/message/add_user_test.go @@ -2,10 +2,10 @@ package message_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -60,7 +60,7 @@ func TestAddUserAction_HandleEvent(t *testing.T) { action := &message.AddUserAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -136,7 +136,7 @@ func TestAddUserAction_HandleEventWithResponseFailed(t *testing.T) { action := &message.AddUserAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -178,7 +178,7 @@ func TestAddUserAction_HandleEventWithAddUserError(t *testing.T) { action := &message.AddUserAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -218,7 +218,7 @@ func TestAddUserAction_HandleEventWithUserAlreadyInRoom(t *testing.T) { action := &message.AddUserAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -262,7 +262,7 @@ func TestAddUserAction_HandleEventWithNoUsername(t *testing.T) { action := &message.AddUserAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -301,7 +301,7 @@ func TestAddUserAction_HandleEventWithUserNotJoined(t *testing.T) { action := &message.AddUserAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -338,7 +338,7 @@ func TestAddUserAction_HandleEventWithJoinedError(t *testing.T) { action := &message.AddUserAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/change_event.go b/internal/connectors/matrix/actions/message/change_event.go index a0f3f2fe..abcabfcd 100644 --- a/internal/connectors/matrix/actions/message/change_event.go +++ b/internal/connectors/matrix/actions/message/change_event.go @@ -1,9 +1,9 @@ package message import ( + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -17,7 +17,7 @@ var changeEventActionRegex = regexp.MustCompile("(?i)(^(change|update|set)[ ]+(r // ChangeEventAction for changing an existing event. type ChangeEventAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -26,7 +26,7 @@ type ChangeEventAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ChangeEventAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ChangeEventAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -75,7 +75,7 @@ func (action *ChangeEventAction) HandleEvent(event *matrix.MessageEvent) { newTime, err := format.ParseTime(event.Content.Body, event.Room.TimeZone, false) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to parse time", "error", err) go action.storer.SendAndStoreResponse( "Ehm, sorry to say that, but I was not able to understand the time to schedule the reminder to.", matrixdb.MessageTypeChangeEventError, @@ -90,7 +90,7 @@ func (action *ChangeEventAction) HandleEvent(event *matrix.MessageEvent) { }) if err != nil || len(events) == 0 { if err != nil { - action.logger.Err(err) + action.logger.Error("failed to list events", "error", err) } go action.storer.SendAndStoreResponse( "This reminder is not in my database.", @@ -104,7 +104,7 @@ func (action *ChangeEventAction) HandleEvent(event *matrix.MessageEvent) { evt.Time = newTime evt, err = action.db.UpdateEvent(evt) if err != nil || len(events) == 0 { - action.logger.Err(err) + action.logger.Error("failed to update event", "error", err) go action.storer.SendAndStoreResponse( "Whups, this did not work, sorry.", matrixdb.MessageTypeChangeEventError, diff --git a/internal/connectors/matrix/actions/message/change_event_test.go b/internal/connectors/matrix/actions/message/change_event_test.go index 09ceaa34..e0885d0f 100644 --- a/internal/connectors/matrix/actions/message/change_event_test.go +++ b/internal/connectors/matrix/actions/message/change_event_test.go @@ -2,10 +2,10 @@ package message_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -52,7 +52,7 @@ func TestChangeEventAction_HandleEvent(t *testing.T) { action := &message.ChangeEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -113,7 +113,7 @@ func TestChangeEventAction_HandleEventWithUpdateError(t *testing.T) { action := &message.ChangeEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -172,7 +172,7 @@ func TestChangeEventAction_HandleEventWithNotFound(t *testing.T) { action := &message.ChangeEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -221,7 +221,7 @@ func TestChangeEventAction_HandleEventWithMissingID(t *testing.T) { action := &message.ChangeEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/change_timezone.go b/internal/connectors/matrix/actions/message/change_timezone.go index aba9bdc7..47d999c7 100644 --- a/internal/connectors/matrix/actions/message/change_timezone.go +++ b/internal/connectors/matrix/actions/message/change_timezone.go @@ -1,10 +1,10 @@ package message import ( + "log/slog" "regexp" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -21,7 +21,7 @@ var timezoneCaptureGroup = regexp.MustCompile("(?i)^set timezone (.*)$") // ChangeTimezoneAction allows setting a timezone for the matrix channel. type ChangeTimezoneAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -30,7 +30,7 @@ type ChangeTimezoneAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ChangeTimezoneAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ChangeTimezoneAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -65,7 +65,7 @@ func (action *ChangeTimezoneAction) HandleEvent(event *matrix.MessageEvent) { } _, err := time.LoadLocation(tz) if err != nil { - action.logger.Infof("failed to load timezone '%s' with: %s", tz, err.Error()) + action.logger.Info("failed to load timezone", "timezone", tz, "error", err) action.storer.SendAndStoreResponse("Sorry, but I do not know what timezone this is.", matrixdb.MessageTypeTimezoneChange, *event) return } @@ -76,7 +76,7 @@ func (action *ChangeTimezoneAction) HandleEvent(event *matrix.MessageEvent) { _, err = action.matrixDB.UpdateRoom(room) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to update room", "error", err) err = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Ups, that did not work 😨", event.Event.ID.String(), @@ -85,7 +85,7 @@ func (action *ChangeTimezoneAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } diff --git a/internal/connectors/matrix/actions/message/change_timezone_test.go b/internal/connectors/matrix/actions/message/change_timezone_test.go index 30eb2633..41200010 100644 --- a/internal/connectors/matrix/actions/message/change_timezone_test.go +++ b/internal/connectors/matrix/actions/message/change_timezone_test.go @@ -2,10 +2,10 @@ package message_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" @@ -53,7 +53,7 @@ func TestChangeTimezoneAction_HandleEvent(t *testing.T) { action := &message.ChangeTimezoneAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -116,7 +116,7 @@ func TestChangeTimezoneAction_HandleEventWithInvalidTimezone(t *testing.T) { action := &message.ChangeTimezoneAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -160,7 +160,7 @@ func TestChangeTimezoneAction_HandleEventWithUpdateError(t *testing.T) { action := &message.ChangeTimezoneAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/delete_event.go b/internal/connectors/matrix/actions/message/delete_event.go index 5dd5f8b4..624de221 100644 --- a/internal/connectors/matrix/actions/message/delete_event.go +++ b/internal/connectors/matrix/actions/message/delete_event.go @@ -2,11 +2,11 @@ package message import ( "errors" + "log/slog" "regexp" "strconv" "strings" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mapping" @@ -20,7 +20,7 @@ var deleteEventActionRegex = regexp.MustCompile("(?i)(^(delete|remove)[ ]*(remin // DeleteEventAction acts as a template for new actions. type DeleteEventAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -29,7 +29,7 @@ type DeleteEventAction struct { } // Configure is called on startup and sets all dependencies. -func (action *DeleteEventAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *DeleteEventAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -59,7 +59,7 @@ func (action *DeleteEventAction) Selector() *regexp.Regexp { func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent) { id, err := getIDFromSentence(event.Content.Body) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to get ID from message", "error", err) err = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Ups, can not find an ID in there.", event.Event.ID.String(), @@ -68,7 +68,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } @@ -78,7 +78,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent) { ChannelID: &event.Channel.ID, }) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to list events", "error", err) err = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Sorry, an error appeared.", event.Event.ID.String(), @@ -87,7 +87,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } @@ -101,7 +101,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } @@ -111,13 +111,13 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent) { dbMessage.EventID = &events[0].ID _, err = action.matrixDB.NewMessage(dbMessage) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to save message to database", "error", err) return } err = action.db.DeleteEvent(&events[0]) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to delete event", "error", err) err = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Sorry, an error appeared.", event.Event.ID.String(), @@ -126,7 +126,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } diff --git a/internal/connectors/matrix/actions/message/delete_event_test.go b/internal/connectors/matrix/actions/message/delete_event_test.go index 7313f0a6..201586b6 100644 --- a/internal/connectors/matrix/actions/message/delete_event_test.go +++ b/internal/connectors/matrix/actions/message/delete_event_test.go @@ -2,10 +2,10 @@ package message_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" @@ -54,7 +54,7 @@ func TestDeleteEventAction_HandleEvent(t *testing.T) { action := &message.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -125,7 +125,7 @@ func TestDeleteEventAction_HandleEventWithDatabaseError(t *testing.T) { action := &message.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -182,7 +182,7 @@ func TestDeleteEventAction_HandleEventWithNewMessageError(t *testing.T) { action := &message.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -229,7 +229,7 @@ func TestDeleteEventAction_HandleEventWithEventNotFound(t *testing.T) { action := &message.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -270,7 +270,7 @@ func TestDeleteEventAction_HandleEventWithListEventsError(t *testing.T) { action := &message.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -311,7 +311,7 @@ func TestDeleteEventAction_HandleEventWithIDNotFound(t *testing.T) { action := &message.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/enable_ical_export.go b/internal/connectors/matrix/actions/message/enable_ical_export.go index 971a97a7..f729713c 100644 --- a/internal/connectors/matrix/actions/message/enable_ical_export.go +++ b/internal/connectors/matrix/actions/message/enable_ical_export.go @@ -2,9 +2,9 @@ package message import ( "errors" + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" @@ -20,7 +20,7 @@ var enableICalExportActionRegex = regexp.MustCompile("(?i)^(ical$|(show|give|lis // EnableICalExportAction enables iCal in a channel. type EnableICalExportAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -30,7 +30,7 @@ type EnableICalExportAction struct { // Configure is called on startup and sets all dependencies. func (action *EnableICalExportAction) Configure( - logger gologger.Logger, + logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, @@ -74,9 +74,9 @@ func (action *EnableICalExportAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } - action.logger.Err(err) + action.logger.Error("failed to get/create iCal output", "error", err) return } @@ -85,7 +85,7 @@ func (action *EnableICalExportAction) HandleEvent(event *matrix.MessageEvent) { msg.Type = matrixdb.MessageTypeIcalExportEnable _, err = action.matrixDB.NewMessage(msg) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to save message to database", "error", err) } msgBuilder := format.Formater{} @@ -102,7 +102,7 @@ func (action *EnableICalExportAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) return } @@ -115,7 +115,7 @@ func (action *EnableICalExportAction) HandleEvent(event *matrix.MessageEvent) { msg.BodyFormatted = response _, err = action.matrixDB.NewMessage(msg) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to save response to database", "error", err) } } diff --git a/internal/connectors/matrix/actions/message/enable_ical_export_test.go b/internal/connectors/matrix/actions/message/enable_ical_export_test.go index 582acd70..c3083a74 100644 --- a/internal/connectors/matrix/actions/message/enable_ical_export_test.go +++ b/internal/connectors/matrix/actions/message/enable_ical_export_test.go @@ -1,10 +1,10 @@ package message_test import ( + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" @@ -56,7 +56,7 @@ func TestEnableICalExportAction_HandleEvent(t *testing.T) { //nolint: dupl action := &message.EnableICalExportAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -131,7 +131,7 @@ func TestEnableICalExportAction_HandleEventWithNoOutput(t *testing.T) { action := &message.EnableICalExportAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/list_commands.go b/internal/connectors/matrix/actions/message/list_commands.go index 5500672f..43bc62af 100644 --- a/internal/connectors/matrix/actions/message/list_commands.go +++ b/internal/connectors/matrix/actions/message/list_commands.go @@ -1,9 +1,9 @@ package message import ( + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reaction" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reply" @@ -19,7 +19,7 @@ var listCommandsRegex = regexp.MustCompile("(?i)^(((show|list)( all| the| my|)( // ListCommandsAction sets the time for the daily reminder. type ListCommandsAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -28,7 +28,7 @@ type ListCommandsAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ListCommandsAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ListCommandsAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB diff --git a/internal/connectors/matrix/actions/message/list_commands_test.go b/internal/connectors/matrix/actions/message/list_commands_test.go index 3259b0a0..07a99187 100644 --- a/internal/connectors/matrix/actions/message/list_commands_test.go +++ b/internal/connectors/matrix/actions/message/list_commands_test.go @@ -1,10 +1,10 @@ package message_test import ( + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -49,7 +49,7 @@ func TestListCommandsAction_HandleEvent(t *testing.T) { action := &message.ListCommandsAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/list_events.go b/internal/connectors/matrix/actions/message/list_events.go index a2214ada..b3e2a76c 100644 --- a/internal/connectors/matrix/actions/message/list_events.go +++ b/internal/connectors/matrix/actions/message/list_events.go @@ -1,9 +1,9 @@ package message import ( + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -18,7 +18,7 @@ var listEventsActionRegex = regexp.MustCompile("(?i)^((list|show)(| all| the)(| // ListEventsAction lists all events. type ListEventsAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -27,7 +27,7 @@ type ListEventsAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ListEventsAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ListEventsAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -67,9 +67,9 @@ func (action *ListEventsAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err2 != nil { - action.logger.Err(err2) + action.logger.Error("failed to send response", "error", err2) } - action.logger.Err(err) + action.logger.Error("failed to list events", "error", err) return } @@ -77,7 +77,7 @@ func (action *ListEventsAction) HandleEvent(event *matrix.MessageEvent) { message.Type = matrixdb.MessageTypeEventList _, err = action.matrixDB.NewMessage(message) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to save message to database", "error", err) } msg := format.Formater{} diff --git a/internal/connectors/matrix/actions/message/list_events_test.go b/internal/connectors/matrix/actions/message/list_events_test.go index bd156111..63ff4d2a 100644 --- a/internal/connectors/matrix/actions/message/list_events_test.go +++ b/internal/connectors/matrix/actions/message/list_events_test.go @@ -2,10 +2,10 @@ package message_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" @@ -52,7 +52,7 @@ func TestListEventsAction_HandleEvent(t *testing.T) { action := &message.ListEventsAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -120,7 +120,7 @@ func TestListEventsAction_HandleEventWithError(t *testing.T) { action := &message.ListEventsAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/new_event.go b/internal/connectors/matrix/actions/message/new_event.go index 1592481c..cd854402 100644 --- a/internal/connectors/matrix/actions/message/new_event.go +++ b/internal/connectors/matrix/actions/message/new_event.go @@ -2,10 +2,10 @@ package message import ( "fmt" + "log/slog" "regexp" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -21,7 +21,7 @@ var newEventActionRegex = regexp.MustCompile(".*") // NewEventAction for new events. Should be the default message handler. type NewEventAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -29,7 +29,7 @@ type NewEventAction struct { } // Configure is called on startup and sets all dependencies. -func (action *NewEventAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *NewEventAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -57,7 +57,7 @@ func (action *NewEventAction) Selector() *regexp.Regexp { func (action *NewEventAction) HandleEvent(event *matrix.MessageEvent) { remindTime, err := format.ParseTime(event.Content.Body, event.Room.TimeZone, false) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to extract time from message", "error", err) _ = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Sorry I was not able to understand the remind date and time from this message", event.Event.ID.String(), @@ -77,7 +77,7 @@ func (action *NewEventAction) HandleEvent(event *matrix.MessageEvent) { InputID: &event.Input.ID, }) if err != nil { - action.logger.Errorf("failed to save event to db: %v", err) + action.logger.Error("failed to save event to database", "error", err) return } @@ -86,7 +86,7 @@ func (action *NewEventAction) HandleEvent(event *matrix.MessageEvent) { message.EventID = &dbEvent.ID _, err = action.matrixDB.NewMessage(message) if err != nil { - action.logger.Errorf("failed to save message to db: %v", err) + action.logger.Error("failed to save message to database", "error", err) return } @@ -103,7 +103,7 @@ func (action *NewEventAction) HandleEvent(event *matrix.MessageEvent) { resp, err := action.messenger.SendResponse(response) if err != nil { - action.logger.Errorf("failed sending out message: %v", err) + action.logger.Error("failed to send out message", "error", err) return } @@ -119,7 +119,7 @@ func (action *NewEventAction) HandleEvent(event *matrix.MessageEvent) { message.EventID = &dbEvent.ID _, err = action.matrixDB.NewMessage(message) if err != nil { - action.logger.Infof("Could not add message to database: %v", err) + action.logger.Warn("failed to add message to database", "error", err) } }(event, dbEvent) @@ -130,7 +130,7 @@ func (action *NewEventAction) HandleEvent(event *matrix.MessageEvent) { ChannelExternalIdentifier: event.Room.RoomID, }) if err != nil { - action.logger.Err(err) + action.logger.Warn("failed to send reaction", "error", err) } } } diff --git a/internal/connectors/matrix/actions/message/new_event_test.go b/internal/connectors/matrix/actions/message/new_event_test.go index c070bc43..88c88cff 100644 --- a/internal/connectors/matrix/actions/message/new_event_test.go +++ b/internal/connectors/matrix/actions/message/new_event_test.go @@ -3,10 +3,11 @@ package message_test import ( "errors" "fmt" + "log/slog" + "os" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -52,7 +53,7 @@ func TestNewEventAction_HandleEvent(t *testing.T) { action := &message.NewEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.New(slog.NewTextHandler(os.Stdout, nil)), client, msngr, matrixDB, @@ -136,7 +137,7 @@ func TestNewEventAction_HandleEventWithNewMessageError(t *testing.T) { action := &message.NewEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.New(slog.NewTextHandler(os.Stdout, nil)), client, msngr, matrixDB, @@ -189,7 +190,7 @@ func TestNewEventAction_HandleEventWithNewEventError(t *testing.T) { action := &message.NewEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.New(slog.NewTextHandler(os.Stdout, nil)), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/regen_ical_token.go b/internal/connectors/matrix/actions/message/regen_ical_token.go index 53f8e92b..734a20e9 100644 --- a/internal/connectors/matrix/actions/message/regen_ical_token.go +++ b/internal/connectors/matrix/actions/message/regen_ical_token.go @@ -2,9 +2,9 @@ package message import ( "errors" + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" @@ -20,7 +20,7 @@ var regenIcalTokenActionRegex = regexp.MustCompile("(?i)^(make|generate|)[ ]*(re // RegenICalTokenAction enables iCal in a channel. type RegenICalTokenAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -30,7 +30,7 @@ type RegenICalTokenAction struct { // Configure is called on startup and sets all dependencies. func (action *RegenICalTokenAction) Configure( - logger gologger.Logger, + logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, @@ -70,7 +70,7 @@ func (action *RegenICalTokenAction) HandleEvent(event *matrix.MessageEvent) { if errors.Is(err, ical.ErrNotFound) { msg = "It looks like iCal output is not set up for this channel. Set it up first." } else { - action.logger.Err(err) + action.logger.Error("failed to get iCal output", "error", err) } err = action.messenger.SendResponseAsync(messenger.PlainTextResponse( msg, @@ -80,7 +80,7 @@ func (action *RegenICalTokenAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) } return } @@ -90,7 +90,7 @@ func (action *RegenICalTokenAction) HandleEvent(event *matrix.MessageEvent) { msg.Type = matrixdb.MessageTypeIcalRegenToken _, err = action.matrixDB.NewMessage(msg) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to store message to databse", "error", err) } msgBuilder := format.Formater{} @@ -107,7 +107,7 @@ func (action *RegenICalTokenAction) HandleEvent(event *matrix.MessageEvent) { event.Room.RoomID, )) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to send response", "error", err) return } @@ -120,7 +120,7 @@ func (action *RegenICalTokenAction) HandleEvent(event *matrix.MessageEvent) { msg.BodyFormatted = response _, err = action.matrixDB.NewMessage(msg) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to store response to database", "error", err) } } diff --git a/internal/connectors/matrix/actions/message/regen_ical_token_test.go b/internal/connectors/matrix/actions/message/regen_ical_token_test.go index 2ca42257..1ff60878 100644 --- a/internal/connectors/matrix/actions/message/regen_ical_token_test.go +++ b/internal/connectors/matrix/actions/message/regen_ical_token_test.go @@ -1,10 +1,10 @@ package message_test import ( + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" @@ -56,7 +56,7 @@ func TestRegenICalTokenAction_HandleEvent(t *testing.T) { //nolint: dupl action := &message.RegenICalTokenAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -129,7 +129,7 @@ func TestRegenICalTokenAction_HandleEventWithNoOutput(t *testing.T) { action := &message.RegenICalTokenAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/message/set_daily_reminder.go b/internal/connectors/matrix/actions/message/set_daily_reminder.go index c39171df..b04fd97c 100644 --- a/internal/connectors/matrix/actions/message/set_daily_reminder.go +++ b/internal/connectors/matrix/actions/message/set_daily_reminder.go @@ -2,10 +2,10 @@ package message import ( "fmt" + "log/slog" "regexp" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -20,7 +20,7 @@ var setDailyReminderRegex = regexp.MustCompile("(?i)^(set|update|change|)[ ]*(th // SetDailyReminderAction sets the time for the daily reminder. type SetDailyReminderAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -29,7 +29,7 @@ type SetDailyReminderAction struct { } // Configure is called on startup and sets all dependencies. -func (action *SetDailyReminderAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *SetDailyReminderAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -61,12 +61,12 @@ func (action *SetDailyReminderAction) HandleEvent(event *matrix.MessageEvent) { dbMsg.Type = matrixdb.MessageTypeSetDailyReminder _, err := action.matrixDB.NewMessage(dbMsg) if err != nil { - action.logger.Errorf("Could not save message: %s", err.Error()) + action.logger.Error("failed to store message to database", "error", err) } timeRemind, err := format.ParseTime(event.Content.Body, event.Room.TimeZone, true) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to parse time", "error", err) msg := "Sorry, I was not able to understand the time." go action.storer.SendAndStoreMessage(msg, msg, matrixdb.MessageTypeSetDailyReminderError, *event) return @@ -76,7 +76,7 @@ func (action *SetDailyReminderAction) HandleEvent(event *matrix.MessageEvent) { event.Channel.DailyReminder = &minutesSinceMidnight _, err = action.db.UpdateChannel(event.Channel) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to update channel", "error", err) msg := "Whups, could not save that change. Sorry, try again later." go action.storer.SendAndStoreMessage(msg, msg, matrixdb.MessageTypeSetDailyReminderError, *event) return diff --git a/internal/connectors/matrix/actions/message/set_daily_reminder_test.go b/internal/connectors/matrix/actions/message/set_daily_reminder_test.go index 149bc02d..b6296ae0 100644 --- a/internal/connectors/matrix/actions/message/set_daily_reminder_test.go +++ b/internal/connectors/matrix/actions/message/set_daily_reminder_test.go @@ -2,12 +2,12 @@ package message_test import ( "errors" + "log/slog" "testing" "time" _ "time/tzdata" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/message" @@ -55,7 +55,7 @@ func TestSetDailyReminderAction_HandleEvent(t *testing.T) { action := &message.SetDailyReminderAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -119,7 +119,7 @@ func TestSetDailyReminderAction_HandleEvent_WithTimezone(t *testing.T) { action := &message.SetDailyReminderAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -186,7 +186,7 @@ func TestSetDailyReminderAction_HandleEventWithUpdateChannelError(t *testing.T) action := &message.SetDailyReminderAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -246,7 +246,7 @@ func TestSetDailyReminderAction_HandleEventWithNewMessageError(t *testing.T) { action := &message.SetDailyReminderAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/reaction/_action.go.example b/internal/connectors/matrix/actions/reaction/_action.go.example index 8347afcb..ccf43bac 100644 --- a/internal/connectors/matrix/actions/reaction/_action.go.example +++ b/internal/connectors/matrix/actions/reaction/_action.go.example @@ -1,7 +1,8 @@ package reaction import ( - "github.com/CubicrootXYZ/gologger" + "log/slog" + "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -11,7 +12,7 @@ import ( // ExampleAction acts as a template for new actions. type ExampleAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -19,7 +20,7 @@ type ExampleAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ExampleAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ExampleAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -46,5 +47,5 @@ func (action *ExampleAction) Selector() []string { // HandleEvent is where the reaction event and the related message get's send to if it matches the Selector. func (action *ExampleAction) HandleEvent(event *matrix.ReactionEvent, reactionToMessage *matrixdb.MatrixMessage) { - action.logger.Infof("Example action called") + action.logger.Info("Example action called") } diff --git a/internal/connectors/matrix/actions/reaction/add_time.go b/internal/connectors/matrix/actions/reaction/add_time.go index 172ce58b..ed622e59 100644 --- a/internal/connectors/matrix/actions/reaction/add_time.go +++ b/internal/connectors/matrix/actions/reaction/add_time.go @@ -2,9 +2,9 @@ package reaction import ( "fmt" + "log/slog" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -15,7 +15,7 @@ import ( // AddTimeAction adds time to an event based on reactions. type AddTimeAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -23,7 +23,7 @@ type AddTimeAction struct { } // Configure is called on startup and sets all dependencies. -func (action *AddTimeAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *AddTimeAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -51,16 +51,14 @@ func (action *AddTimeAction) Selector() []string { // HandleEvent is where the reaction event and the related message get's send to if it matches the Selector. func (action *AddTimeAction) HandleEvent(event *matrix.ReactionEvent, reactionToMessage *matrixdb.MatrixMessage) { - l := action.logger.WithFields( - map[string]any{ - "reaction": event.Content.RelatesTo.Key, - "room": reactionToMessage.RoomID, - "related_message": reactionToMessage.ID, - "user": event.Event.Sender, - }, + l := action.logger.With( + "matrix.reaction.key", event.Content.RelatesTo.Key, + "matrix.room.id", reactionToMessage.RoomID, + "matrix.related_message.id", reactionToMessage.ID, + "matrix.sender", event.Event.Sender, ) if reactionToMessage.EventID == nil || reactionToMessage.Event == nil { - l.Infof("skipping because message does not relate to any event") + l.Info("skipping because message does not relate to any event") return } @@ -70,7 +68,7 @@ func (action *AddTimeAction) HandleEvent(event *matrix.ReactionEvent, reactionTo _, err := action.db.UpdateEvent(evt) if err != nil { - l.Err(err) + l.Error("failed to update event", "error", err) _ = action.messenger.SendMessageAsync(messenger.PlainTextMessage( "Whoopsie, can not update the event as requested.", event.Room.RoomID, @@ -89,7 +87,7 @@ func (action *AddTimeAction) HandleEvent(event *matrix.ReactionEvent, reactionTo event.Room.RoomID, )) if err != nil { - l.Err(err) + l.Error("failed to send response", "error", err) } } @@ -128,6 +126,6 @@ func (action *AddTimeAction) addTimeToEvent(reactionKey string, event *database. event.Time = event.Time.Add(7 * 24 * time.Hour) } default: - action.logger.Errorf("do not know what time to add for key '%s'", reactionKey) + action.logger.Error("unknown reaction key", "matrix.reaction.key", reactionKey) } } diff --git a/internal/connectors/matrix/actions/reaction/add_time_test.go b/internal/connectors/matrix/actions/reaction/add_time_test.go index 1d905d01..c12df277 100644 --- a/internal/connectors/matrix/actions/reaction/add_time_test.go +++ b/internal/connectors/matrix/actions/reaction/add_time_test.go @@ -2,9 +2,9 @@ package reaction_test import ( "errors" + "log/slog" "testing" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reaction" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -60,7 +60,7 @@ func TestAddTimeAction_HandleEvent(t *testing.T) { action := &reaction.AddTimeAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/reaction/delete_event.go b/internal/connectors/matrix/actions/reaction/delete_event.go index 296a5ca1..eda903be 100644 --- a/internal/connectors/matrix/actions/reaction/delete_event.go +++ b/internal/connectors/matrix/actions/reaction/delete_event.go @@ -1,7 +1,8 @@ package reaction import ( - "github.com/CubicrootXYZ/gologger" + "log/slog" + "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -11,7 +12,7 @@ import ( // DeleteEventAction takes cafe of delete requests via reactions. type DeleteEventAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -19,7 +20,7 @@ type DeleteEventAction struct { } // Configure is called on startup and sets all dependencies. -func (action *DeleteEventAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *DeleteEventAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -46,16 +47,14 @@ func (action *DeleteEventAction) Selector() []string { // HandleEvent is where the reaction event and the related message get's send to if it matches the Selector. func (action *DeleteEventAction) HandleEvent(event *matrix.ReactionEvent, reactionToMessage *matrixdb.MatrixMessage) { - l := action.logger.WithFields( - map[string]any{ - "reaction": event.Content.RelatesTo.Key, - "room": reactionToMessage.RoomID, - "related_message": reactionToMessage.ID, - "user": event.Event.Sender, - }, + l := action.logger.With( + "matrix.reaction.key", event.Content.RelatesTo.Key, + "matrix.room.id", reactionToMessage.RoomID, + "matrix.related_message.id", reactionToMessage.ID, + "matrix.sender", event.Event.Sender, ) if reactionToMessage.EventID == nil || reactionToMessage.Event == nil { - l.Infof("skipping because message does not relate to any event") + l.Info("skipping because message does not relate to any event") return } @@ -64,7 +63,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.ReactionEvent, reacti _, err := action.db.UpdateEvent(evt) if err != nil { - l.Err(err) + l.Error("failed to update event", "error", err) _ = action.messenger.SendMessageAsync(messenger.PlainTextMessage( "Whoopsie, can not delete the event as requested.", event.Room.RoomID, @@ -82,7 +81,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.ReactionEvent, reacti event.Room.RoomID, )) if err != nil { - action.logger.Errorf("failed to send message: %w", err) + action.logger.Error("failed to send response", "error", err) return } @@ -92,7 +91,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.ReactionEvent, reacti EventID: reactionToMessage.EventID, }) if err != nil { - action.logger.Errorf("failed to list messages for event: %w", err) + action.logger.Error("failed to list messages", "error", err) return } @@ -102,7 +101,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.ReactionEvent, reacti ChannelExternalIdentifier: event.Room.RoomID, }) if err != nil { - action.logger.Errorf("failed to delete message: %w", err) + action.logger.Error("failed to delete message", "error", err) } } } diff --git a/internal/connectors/matrix/actions/reaction/delete_event_test.go b/internal/connectors/matrix/actions/reaction/delete_event_test.go index 4993f105..59b00dd6 100644 --- a/internal/connectors/matrix/actions/reaction/delete_event_test.go +++ b/internal/connectors/matrix/actions/reaction/delete_event_test.go @@ -2,9 +2,9 @@ package reaction_test import ( "errors" + "log/slog" "testing" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reaction" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -60,7 +60,7 @@ func TestDeleteAction_HandleEvent(t *testing.T) { action := &reaction.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/reaction/mark_done.go b/internal/connectors/matrix/actions/reaction/mark_done.go index 9a690f8c..52d06d90 100644 --- a/internal/connectors/matrix/actions/reaction/mark_done.go +++ b/internal/connectors/matrix/actions/reaction/mark_done.go @@ -1,7 +1,8 @@ package reaction import ( - "github.com/CubicrootXYZ/gologger" + "log/slog" + "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -11,7 +12,7 @@ import ( // MarkDoneAction takes cafe of delete requests via reactions. type MarkDoneAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -19,7 +20,7 @@ type MarkDoneAction struct { } // Configure is called on startup and sets all dependencies. -func (action *MarkDoneAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *MarkDoneAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -46,16 +47,14 @@ func (action *MarkDoneAction) Selector() []string { // HandleEvent is where the reaction event and the related message get's send to if it matches the Selector. func (action *MarkDoneAction) HandleEvent(event *matrix.ReactionEvent, reactionToMessage *matrixdb.MatrixMessage) { - l := action.logger.WithFields( - map[string]any{ - "reaction": event.Content.RelatesTo.Key, - "room": reactionToMessage.RoomID, - "related_message": reactionToMessage.ID, - "user": event.Event.Sender, - }, + l := action.logger.With( + "matrix.reaction.key", event.Content.RelatesTo.Key, + "matrix.room.id", reactionToMessage.RoomID, + "matrix.related_message.id", reactionToMessage.ID, + "matrix.sender", event.Event.Sender, ) if reactionToMessage.EventID == nil || reactionToMessage.Event == nil { - l.Infof("skipping because message does not relate to any event") + l.Info("skipping because message does not relate to any event") return } @@ -65,7 +64,7 @@ func (action *MarkDoneAction) HandleEvent(event *matrix.ReactionEvent, reactionT _, err := action.db.UpdateEvent(evt) if err != nil { - l.Err(err) + l.Error("failed to update event", "error", err) _ = action.messenger.SendMessageAsync(messenger.PlainTextMessage( "Whoopsie, can not update the event as requested.", event.Room.RoomID, @@ -79,6 +78,6 @@ func (action *MarkDoneAction) HandleEvent(event *matrix.ReactionEvent, reactionT ChannelExternalIdentifier: reactionToMessage.Room.RoomID, }) if err != nil { - l.Err(err) + l.Error("failed to delete message", "error", err) } } diff --git a/internal/connectors/matrix/actions/reaction/mark_done_test.go b/internal/connectors/matrix/actions/reaction/mark_done_test.go index 85550523..536e4660 100644 --- a/internal/connectors/matrix/actions/reaction/mark_done_test.go +++ b/internal/connectors/matrix/actions/reaction/mark_done_test.go @@ -2,10 +2,10 @@ package reaction_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reaction" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -61,7 +61,7 @@ func TestMarkDoneAction_HandleEvent(t *testing.T) { action := &reaction.MarkDoneAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/reaction/reschdule_repeating.go b/internal/connectors/matrix/actions/reaction/reschdule_repeating.go index a81974e7..6e2d8da2 100644 --- a/internal/connectors/matrix/actions/reaction/reschdule_repeating.go +++ b/internal/connectors/matrix/actions/reaction/reschdule_repeating.go @@ -1,9 +1,9 @@ package reaction import ( + "log/slog" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -13,7 +13,7 @@ import ( // RescheduleRepeatingAction takes care of rescheduling a repeating event. type RescheduleRepeatingAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -21,7 +21,7 @@ type RescheduleRepeatingAction struct { } // Configure is called on startup and sets all dependencies. -func (action *RescheduleRepeatingAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *RescheduleRepeatingAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -48,16 +48,14 @@ func (action *RescheduleRepeatingAction) Selector() []string { // HandleEvent is where the reaction event and the related message get's send to if it matches the Selector. func (action *RescheduleRepeatingAction) HandleEvent(event *matrix.ReactionEvent, reactionToMessage *matrixdb.MatrixMessage) { - l := action.logger.WithFields( - map[string]any{ - "reaction": event.Content.RelatesTo.Key, - "room": reactionToMessage.RoomID, - "related_message": reactionToMessage.ID, - "user": event.Event.Sender, - }, + l := action.logger.With( + "matrix.reaction.key", event.Content.RelatesTo.Key, + "matrix.room.id", reactionToMessage.RoomID, + "matrix.related_message.id", reactionToMessage.ID, + "matrix.sender", event.Event.Sender, ) if reactionToMessage.EventID == nil || reactionToMessage.Event == nil { - l.Infof("skipping because message does not relate to any event") + l.Info("skipping because message does not relate to any event") return } @@ -72,7 +70,7 @@ func (action *RescheduleRepeatingAction) HandleEvent(event *matrix.ReactionEvent } _, err := action.db.NewEvent(newEvt) if err != nil { - l.Err(err) + l.Error("failed to save event to database", "error", err) _ = action.messenger.SendMessageAsync(messenger.PlainTextMessage( "Whoopsie, can not update the event as requested.", event.Room.RoomID, @@ -85,6 +83,6 @@ func (action *RescheduleRepeatingAction) HandleEvent(event *matrix.ReactionEvent ChannelExternalIdentifier: reactionToMessage.Room.RoomID, }) if err != nil { - l.Err(err) + l.Error("failed to delete message", "error", err) } } diff --git a/internal/connectors/matrix/actions/reaction/reschedule_repeating_test.go b/internal/connectors/matrix/actions/reaction/reschedule_repeating_test.go index c8b4d429..87e70b62 100644 --- a/internal/connectors/matrix/actions/reaction/reschedule_repeating_test.go +++ b/internal/connectors/matrix/actions/reaction/reschedule_repeating_test.go @@ -2,9 +2,9 @@ package reaction_test import ( "errors" + "log/slog" "testing" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reaction" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -60,7 +60,7 @@ func TestRescheduleRepeatingAction_HandleEvent(t *testing.T) { action := &reaction.RescheduleRepeatingAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/reply/_action.go.example b/internal/connectors/matrix/actions/reply/_action.go.example index 46d8690a..04575be7 100644 --- a/internal/connectors/matrix/actions/reply/_action.go.example +++ b/internal/connectors/matrix/actions/reply/_action.go.example @@ -1,9 +1,9 @@ package reply import ( + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/messenger" @@ -13,7 +13,7 @@ import ( // ExampleAction acts as a template for new actions. type ExampleAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -21,7 +21,7 @@ type ExampleAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ExampleAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ExampleAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -48,5 +48,5 @@ func (action *ExampleAction) Selector() *regexp.Regexp { // HandleEvent is where the message event get's send to if it matches the Selector. func (action *ExampleAction) HandleEvent(event *matrix.MessageEvent, replyToMessage *matrixdb.MatrixMessage) { - action.logger.Infof("Example action called") + action.logger.Info("Example action called") } diff --git a/internal/connectors/matrix/actions/reply/change_time.go b/internal/connectors/matrix/actions/reply/change_time.go index e97982f0..f1cee775 100644 --- a/internal/connectors/matrix/actions/reply/change_time.go +++ b/internal/connectors/matrix/actions/reply/change_time.go @@ -2,9 +2,9 @@ package reply import ( "fmt" + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -19,7 +19,7 @@ var changeTimeRegex = regexp.MustCompile(".*") // ChangeTimeAction acts as a template for new actions. type ChangeTimeAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -28,7 +28,7 @@ type ChangeTimeAction struct { } // Configure is called on startup and sets all dependencies. -func (action *ChangeTimeAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *ChangeTimeAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -58,13 +58,13 @@ func (action *ChangeTimeAction) Selector() *regexp.Regexp { func (action *ChangeTimeAction) HandleEvent(event *matrix.MessageEvent, replyToMessage *matrixdb.MatrixMessage) { if replyToMessage.EventID == nil || replyToMessage.Event == nil { // No event given, can not update anything - action.logger.Debugf("can not update event with event ID nil") + action.logger.Debug("can not update event with event ID nil") return } remindTime, err := format.ParseTime(event.Content.Body, event.Room.TimeZone, false) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to parse time", "error", err) _ = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Sorry I was not able to understand the remind date and time from this message.", event.Event.ID.String(), @@ -80,7 +80,7 @@ func (action *ChangeTimeAction) HandleEvent(event *matrix.MessageEvent, replyToM message.EventID = replyToMessage.EventID _, err = action.matrixDB.NewMessage(message) if err != nil { - action.logger.Errorf("failed to save message to db: %v", err) + action.logger.Error("failed to save message to database", "error", err) return } @@ -88,7 +88,7 @@ func (action *ChangeTimeAction) HandleEvent(event *matrix.MessageEvent, replyToM replyToMessage.Event.Active = true _, err = action.db.UpdateEvent(replyToMessage.Event) if err != nil { - action.logger.Errorf("failed to update event in database: %v", err) + action.logger.Error("failed to update event in database", "error", err) return } diff --git a/internal/connectors/matrix/actions/reply/change_time_test.go b/internal/connectors/matrix/actions/reply/change_time_test.go index 66f0d6f0..dc210aab 100644 --- a/internal/connectors/matrix/actions/reply/change_time_test.go +++ b/internal/connectors/matrix/actions/reply/change_time_test.go @@ -2,10 +2,10 @@ package reply_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reply" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -50,7 +50,7 @@ func TestChangeTimeAction_HandleEvent(t *testing.T) { action := &reply.ChangeTimeAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -103,7 +103,7 @@ func TestChangeTimeAction_HandleEventWithUpdateError(t *testing.T) { action := &reply.ChangeTimeAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -140,7 +140,7 @@ func TestChangeTimeAction_HandleEventWithNewMessageError(t *testing.T) { action := &reply.ChangeTimeAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/reply/delete_event.go b/internal/connectors/matrix/actions/reply/delete_event.go index 6ffcd7d1..9d962ae4 100644 --- a/internal/connectors/matrix/actions/reply/delete_event.go +++ b/internal/connectors/matrix/actions/reply/delete_event.go @@ -1,9 +1,9 @@ package reply import ( + "log/slog" "regexp" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -16,7 +16,7 @@ var deleteEventActionRegex = regexp.MustCompile("(?i)^(delete|remove|cancel)[ ]* // DeleteEventAction deletes an event. type DeleteEventAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -25,7 +25,7 @@ type DeleteEventAction struct { } // Configure is called on startup and sets all dependencies. -func (action *DeleteEventAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *DeleteEventAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -55,13 +55,13 @@ func (action *DeleteEventAction) Selector() *regexp.Regexp { func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent, replyToMessage *matrixdb.MatrixMessage) { if replyToMessage.EventID == nil || replyToMessage.Event == nil { // No event given, can not update anything - action.logger.Debugf("can not delete event with event ID nil") + action.logger.Debug("can not delete event with event ID nil") return } err := action.db.DeleteEvent(replyToMessage.Event) if err != nil { - action.logger.Errorf("failed to update event in database: %w", err) + action.logger.Error("failed to update event in database", "error", err) return } @@ -73,7 +73,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent, replyTo EventID: replyToMessage.EventID, }) if err != nil { - action.logger.Errorf("failed to list messages for event: %w", err) + action.logger.Error("failed to list messages for event", "error", err) return } @@ -83,7 +83,7 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent, replyTo ChannelExternalIdentifier: event.Room.RoomID, }) if err != nil { - action.logger.Errorf("failed to delete message: %w", err) + action.logger.Error("failed to delete message", "error", err) } } @@ -92,6 +92,6 @@ func (action *DeleteEventAction) HandleEvent(event *matrix.MessageEvent, replyTo ChannelExternalIdentifier: event.Room.RoomID, }) if err != nil { - action.logger.Errorf("failed to delete message: %w", err) + action.logger.Error("failed to delete message", "error", err) } } diff --git a/internal/connectors/matrix/actions/reply/delete_event_test.go b/internal/connectors/matrix/actions/reply/delete_event_test.go index 0f723d18..ae669ba5 100644 --- a/internal/connectors/matrix/actions/reply/delete_event_test.go +++ b/internal/connectors/matrix/actions/reply/delete_event_test.go @@ -2,10 +2,10 @@ package reply_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reply" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -50,7 +50,7 @@ func TestDeleteEventAction_HandleEvent(t *testing.T) { action := &reply.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -126,7 +126,7 @@ func TestDeleteEventAction_HandleEventWithFailingListMessages(t *testing.T) { action := &reply.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -180,7 +180,7 @@ func TestDeleteEventAction_HandleEventWithMissingEventID(t *testing.T) { action := &reply.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -209,7 +209,7 @@ func TestDeleteEventAction_HandleEventWithDeleteError(t *testing.T) { action := &reply.DeleteEventAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/actions/reply/make_recurring.go b/internal/connectors/matrix/actions/reply/make_recurring.go index 42b1f36d..706d3ffe 100644 --- a/internal/connectors/matrix/actions/reply/make_recurring.go +++ b/internal/connectors/matrix/actions/reply/make_recurring.go @@ -2,10 +2,10 @@ package reply import ( "fmt" + "log/slog" "regexp" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/gonaturalduration" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" @@ -21,7 +21,7 @@ var makeRecurringActionRegex = regexp.MustCompile("(?i)^(repeat|every|each|alway // MakeRecurringAction makes an event recurring. type MakeRecurringAction struct { - logger gologger.Logger + logger *slog.Logger client mautrixcl.Client messenger messenger.Messenger matrixDB matrixdb.Service @@ -30,7 +30,7 @@ type MakeRecurringAction struct { } // Configure is called on startup and sets all dependencies. -func (action *MakeRecurringAction) Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { +func (action *MakeRecurringAction) Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, _ *matrix.BridgeServices) { action.logger = logger action.client = client action.matrixDB = matrixDB @@ -60,14 +60,14 @@ func (action *MakeRecurringAction) Selector() *regexp.Regexp { func (action *MakeRecurringAction) HandleEvent(event *matrix.MessageEvent, replyToMessage *matrixdb.MatrixMessage) { if replyToMessage.EventID == nil || replyToMessage.Event == nil { // No event given, can not update anything - action.logger.Debugf("can not change event with event ID nil") + action.logger.Debug("can not change event with event ID nil") return } // Get duration from message duration := gonaturalduration.ParseNumber(event.Content.Body) if duration <= time.Minute { - action.logger.Infof("missing duration in message") + action.logger.Info("missing duration in message") _ = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Sorry I was not able to understand the duration from this message.", event.Event.ID.String(), @@ -83,7 +83,7 @@ func (action *MakeRecurringAction) HandleEvent(event *matrix.MessageEvent, reply message.EventID = replyToMessage.EventID _, err := action.matrixDB.NewMessage(message) if err != nil { - action.logger.Errorf("failed to save message to db: %v", err) + action.logger.Error("failed to save message to database", "error", err) return } @@ -93,7 +93,7 @@ func (action *MakeRecurringAction) HandleEvent(event *matrix.MessageEvent, reply dbEvent, err := action.db.UpdateEvent(replyToMessage.Event) if err != nil { - action.logger.Err(err) + action.logger.Error("failed to update event", "error", err) _ = action.messenger.SendResponseAsync(messenger.PlainTextResponse( "Sorry, that failed :/.", event.Event.ID.String(), diff --git a/internal/connectors/matrix/actions/reply/make_recurring_test.go b/internal/connectors/matrix/actions/reply/make_recurring_test.go index 7c3fbfb9..f31114ee 100644 --- a/internal/connectors/matrix/actions/reply/make_recurring_test.go +++ b/internal/connectors/matrix/actions/reply/make_recurring_test.go @@ -2,10 +2,10 @@ package reply_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/actions/reply" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" @@ -50,7 +50,7 @@ func TestMakeRecurringAction_HandleEvent(t *testing.T) { action := &reply.MakeRecurringAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -96,7 +96,7 @@ func TestMakeRecurringAction_HandleEventWithUpdateError(t *testing.T) { action := &reply.MakeRecurringAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, @@ -139,7 +139,7 @@ func TestMakeRecurringAction_HandleEventWithDurationError(t *testing.T) { action := &reply.MakeRecurringAction{} action.Configure( - gologger.New(gologger.LogLevelDebug, 0), + slog.Default(), client, msngr, matrixDB, diff --git a/internal/connectors/matrix/api/api.go b/internal/connectors/matrix/api/api.go index 35f331f7..ecacd66c 100644 --- a/internal/connectors/matrix/api/api.go +++ b/internal/connectors/matrix/api/api.go @@ -1,7 +1,8 @@ package api import ( - "github.com/CubicrootXYZ/gologger" + "log/slog" + "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/api/apictx" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -10,7 +11,7 @@ import ( type api struct { config *Config - logger gologger.Logger + logger *slog.Logger } // Config holds the configuration for the API. @@ -22,7 +23,7 @@ type Config struct { } // New assembles a new API. -func New(config *Config, logger gologger.Logger) API { +func New(config *Config, logger *slog.Logger) API { return &api{ config: config, logger: logger, diff --git a/internal/connectors/matrix/api/api_test.go b/internal/connectors/matrix/api/api_test.go index a738be2c..8cdafe71 100644 --- a/internal/connectors/matrix/api/api_test.go +++ b/internal/connectors/matrix/api/api_test.go @@ -1,9 +1,9 @@ package api_test import ( + "log/slog" "net/http/httptest" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/api" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -19,7 +19,7 @@ func testServer(ctrl *gomock.Controller) (*database.MockService, *matrixdb.MockS Database: db, MatrixDB: matrixDB, DefaultAuthProvider: func(_ *gin.Context) {}, - }, gologger.New(gologger.LogLevelDebug, 0)) + }, slog.Default()) r := gin.New() err := api.RegisterRoutes(r) diff --git a/internal/connectors/matrix/api/room_handlers.go b/internal/connectors/matrix/api/room_handlers.go index d643c500..33ce53bc 100644 --- a/internal/connectors/matrix/api/room_handlers.go +++ b/internal/connectors/matrix/api/room_handlers.go @@ -69,7 +69,7 @@ func (api *api) listInputRoomsHandler(ctx *gin.Context) { rooms, err := api.config.MatrixDB.ListInputRoomsByChannel(channelID) if err != nil { - api.logger.Err(err) + api.logger.Error("failed to list input rooms", "error", err, "channel.id", channelID) response.AbortWithInternalServerError(ctx) return } @@ -98,7 +98,7 @@ func (api *api) listOutputRoomsHandler(ctx *gin.Context) { rooms, err := api.config.MatrixDB.ListOutputRoomsByChannel(channelID) if err != nil { - api.logger.Err(err) + api.logger.Error("failed to list output rooms", "error", err, "channel.id", channelID) response.AbortWithInternalServerError(ctx) return } diff --git a/internal/connectors/matrix/database/service_test.go b/internal/connectors/matrix/database/service_test.go index b9f06719..b12721b9 100644 --- a/internal/connectors/matrix/database/service_test.go +++ b/internal/connectors/matrix/database/service_test.go @@ -4,13 +4,11 @@ import ( "os" "testing" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "gorm.io/driver/mysql" "gorm.io/gorm" ) -var logger gologger.Logger var service database.Service var gormDB *gorm.DB @@ -41,12 +39,7 @@ func getService(gormDB *gorm.DB) database.Service { return service } -func getLogger() gologger.Logger { - return gologger.New(gologger.LogLevelDebug, 0) -} - func TestMain(m *testing.M) { - logger = getLogger() gormDB = getGormDB() service = getService(gormDB) diff --git a/internal/connectors/matrix/message_action_mock.go b/internal/connectors/matrix/message_action_mock.go index f957d4a8..880c02cf 100644 --- a/internal/connectors/matrix/message_action_mock.go +++ b/internal/connectors/matrix/message_action_mock.go @@ -5,10 +5,10 @@ package matrix import ( + slog "log/slog" reflect "reflect" regexp "regexp" - gologger "github.com/CubicrootXYZ/gologger" database "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" mautrixcl "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" messenger "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/messenger" @@ -40,7 +40,7 @@ func (m *MockMessageAction) EXPECT() *MockMessageActionMockRecorder { } // Configure mocks base method. -func (m *MockMessageAction) Configure(arg0 gologger.Logger, arg1 mautrixcl.Client, arg2 messenger.Messenger, arg3 database.Service, arg4 database0.Service, arg5 *BridgeServices) { +func (m *MockMessageAction) Configure(arg0 *slog.Logger, arg1 mautrixcl.Client, arg2 messenger.Messenger, arg3 database.Service, arg4 database0.Service, arg5 *BridgeServices) { m.ctrl.T.Helper() m.ctrl.Call(m, "Configure", arg0, arg1, arg2, arg3, arg4, arg5) } diff --git a/internal/connectors/matrix/message_handler.go b/internal/connectors/matrix/message_handler.go index 79caf9ee..84dfd1e9 100644 --- a/internal/connectors/matrix/message_handler.go +++ b/internal/connectors/matrix/message_handler.go @@ -2,9 +2,9 @@ package matrix import ( "errors" + "log/slog" "strings" - "github.com/CubicrootXYZ/gologger" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -21,12 +21,12 @@ type MessageEvent struct { } func (service *service) MessageEventHandler(_ mautrix.EventSource, evt *event.Event) { - logger := service.logger.WithFields(map[string]any{ - "sender": evt.Sender, - "room": evt.RoomID, - "event_timestamp": evt.Timestamp, - }) - logger.Debugf("new message received") + logger := service.logger.With( + "matrix.sender", evt.Sender, + "matrix.room.id", evt.RoomID, + "matrix.event.timestamp", evt.Timestamp, + ) + logger.Debug("new message received") // Do not answer our own and old messages if evt.Sender.String() == service.botname || evt.Timestamp/1000 <= service.lastMessageFrom.Unix() { @@ -35,7 +35,7 @@ func (service *service) MessageEventHandler(_ mautrix.EventSource, evt *event.Ev room, err := service.matrixDatabase.GetRoomByRoomID(string(evt.RoomID)) if err != nil { - logger.Debugf("do not know room, ignoring message") + logger.Debug("ignoring message", "reason", "unknown room") return } @@ -48,7 +48,7 @@ func (service *service) MessageEventHandler(_ mautrix.EventSource, evt *event.Ev } } if !isUserKnown { - logger.Debugf("do not know user, ignoring message") + logger.Debug("ignoring message", "reason", "unknown user") return } @@ -58,12 +58,12 @@ func (service *service) MessageEventHandler(_ mautrix.EventSource, evt *event.Ev return } if !errors.Is(err, matrixdb.ErrNotFound) { - logger.Err(err) + logger.Error("failed to get message from database", "error", err) } msgEvt, err := service.parseMessageEvent(evt, room) if err != nil { - logger.Infof("can not handle event: " + err.Error()) + logger.Info("failed to parse message event", "error", err) return } @@ -76,41 +76,38 @@ func (service *service) MessageEventHandler(_ mautrix.EventSource, evt *event.Ev } } -func (service *service) findMatchingReplyAction(msgEvent *MessageEvent, logger gologger.Logger) { +func (service *service) findMatchingReplyAction(msgEvent *MessageEvent, logger *slog.Logger) { replyToMessage, err := service.matrixDatabase.GetMessageByID(msgEvent.Content.RelatesTo.InReplyTo.EventID.String()) if err != nil { - logger.Infof( - "discarding message, can not find the message '%s' it replies to: %s", - msgEvent.Content.RelatesTo.InReplyTo.EventID.String(), - err.Error(), - ) + logger.Info("failed to get replied to message from database", "error", err, + "matrix.event.id", msgEvent.Content.RelatesTo.InReplyTo.EventID.String()) return } msg := strings.ToLower(format.StripReply(msgEvent.Content.Body)) for i := range service.config.ReplyActions { if service.config.ReplyActions[i].Selector().MatchString(msg) { - logger.Infof("moving event to reply action: %s", service.config.ReplyActions[i].Name()) + logger.Info("moving event to reply action", "action.name", service.config.ReplyActions[i].Name()) service.config.ReplyActions[i].HandleEvent(msgEvent, replyToMessage) return } } - logger.Infof("moving event to default reply action") + logger.Info("moving event to default reply action") service.config.DefaultReplyAction.HandleEvent(msgEvent, replyToMessage) } -func (service *service) findMatchingMessageAction(msgEvent *MessageEvent, logger gologger.Logger) { +func (service *service) findMatchingMessageAction(msgEvent *MessageEvent, logger *slog.Logger) { msg := strings.ToLower(msgEvent.Content.Body) for i := range service.config.MessageActions { if service.config.MessageActions[i].Selector().MatchString(msg) { - logger.Infof("moving event to message action: %s", service.config.MessageActions[i].Name()) + logger.Info("moving event to message action", "action.name", service.config.MessageActions[i].Name()) service.config.MessageActions[i].HandleEvent(msgEvent) return } } - logger.Infof("moving event to default message action") + logger.Info("moving event to default message action") service.config.DefaultMessageAction.HandleEvent(msgEvent) } diff --git a/internal/connectors/matrix/message_handler_test.go b/internal/connectors/matrix/message_handler_test.go index e224fda4..01ae838c 100644 --- a/internal/connectors/matrix/message_handler_test.go +++ b/internal/connectors/matrix/message_handler_test.go @@ -2,11 +2,12 @@ package matrix import ( "errors" + "log/slog" + "os" "regexp" "testing" "time" - "github.com/CubicrootXYZ/gologger" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/messenger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -65,7 +66,7 @@ func testService(ctrl *gomock.Controller) (service, *fixture) { }, database: fx.db, matrixDatabase: fx.matrixDB, - logger: gologger.New(gologger.LogLevelDebug, 0), + logger: slog.New(slog.NewTextHandler(os.Stdout, nil)), botname: "@bot:example.com", messenger: fx.messenger, } diff --git a/internal/connectors/matrix/messenger/delete.go b/internal/connectors/matrix/messenger/delete.go index be9361f8..5c24d267 100644 --- a/internal/connectors/matrix/messenger/delete.go +++ b/internal/connectors/matrix/messenger/delete.go @@ -41,15 +41,15 @@ func (messenger *service) deleteMessage(deleteAction *Delete, retries uint, retr } else if errors.Is(err, mautrix.MLimitExceeded) { // Rate limit is exceeded so wait until we can send requests again messenger.encounteredRateLimit() - messenger.logger.Infof("Deleting message is stopped since we ran in a rate limit") + messenger.logger.Info("deleting message is stopped since we ran in a rate limit") continue } else if errors.Is(err, mautrix.MForbidden) || errors.Is(err, mautrix.MUnknownToken) || errors.Is(err, mautrix.MMissingToken) || errors.Is(err, mautrix.MBadJSON) || errors.Is(err, mautrix.MNotJSON) || errors.Is(err, mautrix.MUnsupportedRoomVersion) || errors.Is(err, mautrix.MIncompatibleRoomVersion) { // Errors indicating that the request is invalid, do not try again - messenger.logger.Infof("Deleting message failed with error: " + err.Error()) + messenger.logger.Info("deleting message failed", "error", err) return err } - messenger.logger.Infof(fmt.Sprintf("Deleting message failed in try %d from try %d with error: %s", retries, maxRetries, err.Error())) + messenger.logger.Info(fmt.Sprintf("Deleting message failed in try %d from try %d with error: %s", retries, maxRetries, err.Error())) retries-- time.Sleep(retryTime * (time.Duration(maxRetries) - time.Duration(retries))) @@ -59,6 +59,6 @@ func (messenger *service) deleteMessage(deleteAction *Delete, retries uint, retr err = ErrRetriesExceeded } - messenger.logger.Infof("Deleting message failed and retries are exceeded. Error is: " + err.Error()) + messenger.logger.Info("deleting message failed and retries are exceeded", "error", err) return err } diff --git a/internal/connectors/matrix/messenger/message.go b/internal/connectors/matrix/messenger/message.go index b53b0a0b..575ae1cc 100644 --- a/internal/connectors/matrix/messenger/message.go +++ b/internal/connectors/matrix/messenger/message.go @@ -113,15 +113,15 @@ func (messenger *service) sendMessage(messageEvent *messageEvent, channel string } else if errors.Is(err, mautrix.MLimitExceeded) { // Rate limit is exceeded so wait until we can send requests again messenger.encounteredRateLimit() - messenger.logger.Infof("Sending message is stopped since we ran in a rate limit") + messenger.logger.Info("sending message is stopped since we ran in a rate limit") continue } else if errors.Is(err, mautrix.MForbidden) || errors.Is(err, mautrix.MUnknownToken) || errors.Is(err, mautrix.MMissingToken) || errors.Is(err, mautrix.MBadJSON) || errors.Is(err, mautrix.MNotJSON) || errors.Is(err, mautrix.MUnsupportedRoomVersion) || errors.Is(err, mautrix.MIncompatibleRoomVersion) { // Errors indicating that the request is invalid, do not try again - messenger.logger.Infof("Sending message failed with error: " + err.Error()) + messenger.logger.Info("sending message failed", "error", err) return nil, err } - messenger.logger.Infof("Sending message failed in try %d from try %d with error: %s", retries, maxRetries, err.Error()) + messenger.logger.Info("sending message failed", "try", retries, "max_tries", maxRetries, "error", err) retries-- time.Sleep(retryTime * (time.Duration(maxRetries) - time.Duration(retries))) @@ -131,7 +131,7 @@ func (messenger *service) sendMessage(messageEvent *messageEvent, channel string err = ErrRetriesExceeded } - messenger.logger.Infof("Sending message failed and retries are exceeded. Error is: " + err.Error()) + messenger.logger.Info("sending message failed and retries are exceeded", "error", err) return nil, err } diff --git a/internal/connectors/matrix/messenger/redact.go b/internal/connectors/matrix/messenger/redact.go index 6d4f1855..9e1d4a35 100644 --- a/internal/connectors/matrix/messenger/redact.go +++ b/internal/connectors/matrix/messenger/redact.go @@ -40,15 +40,15 @@ func (messenger *service) sendRedact(roomID string, eventID string, retries uint } else if errors.Is(err, mautrix.MLimitExceeded) { // Rate limit is exceeded so wait until we can send requests again messenger.encounteredRateLimit() - messenger.logger.Infof("Sending message is stopped since we ran in a rate limit") + messenger.logger.Info("sending message is stopped since we ran in a rate limit") continue } else if errors.Is(err, mautrix.MForbidden) || errors.Is(err, mautrix.MUnknownToken) || errors.Is(err, mautrix.MMissingToken) || errors.Is(err, mautrix.MBadJSON) || errors.Is(err, mautrix.MNotJSON) || errors.Is(err, mautrix.MUnsupportedRoomVersion) || errors.Is(err, mautrix.MIncompatibleRoomVersion) { // Errors indicating that the request is invalid, do not try again - messenger.logger.Infof("Sending message failed with error: " + err.Error()) + messenger.logger.Info("sending message failed", "error", err) return err } - messenger.logger.Infof(fmt.Sprintf("Sending message failed in try %d from try %d with error: %s", retries, maxRetries, err.Error())) + messenger.logger.Info(fmt.Sprintf("Sending message failed in try %d from try %d with error: %s", retries, maxRetries, err.Error())) retries-- time.Sleep(retryTime * (time.Duration(maxRetries) - time.Duration(retries))) @@ -58,6 +58,6 @@ func (messenger *service) sendRedact(roomID string, eventID string, retries uint err = ErrRetriesExceeded } - messenger.logger.Infof("Sending message failed and retries are exceeded. Error is: " + err.Error()) + messenger.logger.Info("sending message failed and retries are exceeded", "error", err) return err } diff --git a/internal/connectors/matrix/messenger/service.go b/internal/connectors/matrix/messenger/service.go index c11c2963..d5ac264c 100644 --- a/internal/connectors/matrix/messenger/service.go +++ b/internal/connectors/matrix/messenger/service.go @@ -1,10 +1,10 @@ package messenger import ( + "log/slog" "sync" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "maunium.net/go/mautrix" "maunium.net/go/mautrix/event" @@ -16,7 +16,7 @@ type service struct { config *Config client MatrixClient db database.Service - logger gologger.Logger + logger *slog.Logger state *state } @@ -29,7 +29,7 @@ type state struct { rateLimitedUntilMutex sync.Mutex } -func NewMessenger(config *Config, db database.Service, matrixClient MatrixClient, logger gologger.Logger) (Messenger, error) { +func NewMessenger(config *Config, db database.Service, matrixClient MatrixClient, logger *slog.Logger) (Messenger, error) { return &service{ roomUserCache: make(roomCache), config: config, @@ -44,7 +44,7 @@ func NewMessenger(config *Config, db database.Service, matrixClient MatrixClient // sendMessageEvent sends a message event to matrix, will take care of encryption if available func (messenger *service) sendMessageEvent(messageEvent *messageEvent, roomID string, eventType event.Type) (*mautrix.RespSendEvent, error) { - messenger.logger.Infof("Sending message to room %s", roomID) + messenger.logger.Info("sending message", "matrix.room.id", roomID) return messenger.client.SendMessageEvent(id.RoomID(roomID), eventType, &messageEvent) } diff --git a/internal/connectors/matrix/msghelper/send_and_store.go b/internal/connectors/matrix/msghelper/send_and_store.go index 5ceffbbd..fc52530a 100644 --- a/internal/connectors/matrix/msghelper/send_and_store.go +++ b/internal/connectors/matrix/msghelper/send_and_store.go @@ -1,7 +1,8 @@ package msghelper import ( - "github.com/CubicrootXYZ/gologger" + "log/slog" + "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/messenger" @@ -11,11 +12,11 @@ import ( type Storer struct { db matrixdb.Service messenger messenger.Messenger - logger gologger.Logger + logger *slog.Logger } // NewStorer assembles a new storer. -func NewStorer(db matrixdb.Service, messenger messenger.Messenger, logger gologger.Logger) *Storer { +func NewStorer(db matrixdb.Service, messenger messenger.Messenger, logger *slog.Logger) *Storer { return &Storer{ db: db, messenger: messenger, @@ -27,7 +28,7 @@ func NewStorer(db matrixdb.Service, messenger messenger.Messenger, logger gologg func (storer *Storer) SendAndStoreMessage(message, messageFormatted string, messageType matrixdb.MatrixMessageType, event matrix.MessageEvent) { resp, err := storer.messenger.SendMessage(messenger.HTMLMessage(message, messageFormatted, event.Room.RoomID)) if err != nil { - storer.logger.Err(err) + storer.logger.Error("failed to send message", "error", err) return } @@ -45,7 +46,7 @@ func (storer *Storer) SendAndStoreMessage(message, messageFormatted string, mess _, err = storer.db.NewMessage(&dbMessage) if err != nil { - storer.logger.Err(err) + storer.logger.Error("failed to store message to database", "error", err) } } @@ -63,7 +64,7 @@ func (storer *Storer) SendAndStoreResponse(message string, messageType matrixdb. event.Room.RoomID, )) if err != nil { - storer.logger.Err(err) + storer.logger.Error("failed to send response", "error", err) return } @@ -85,7 +86,7 @@ func (storer *Storer) SendAndStoreResponse(message string, messageType matrixdb. _, err = storer.db.NewMessage(&dbMessage) if err != nil { - storer.logger.Err(err) + storer.logger.Error("failed to store response", "error", err) } } diff --git a/internal/connectors/matrix/reaction_action_mock.go b/internal/connectors/matrix/reaction_action_mock.go index e573d4dc..6f3035b9 100644 --- a/internal/connectors/matrix/reaction_action_mock.go +++ b/internal/connectors/matrix/reaction_action_mock.go @@ -5,9 +5,9 @@ package matrix import ( + slog "log/slog" reflect "reflect" - gologger "github.com/CubicrootXYZ/gologger" database "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" mautrixcl "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" messenger "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/messenger" @@ -39,7 +39,7 @@ func (m *MockReactionAction) EXPECT() *MockReactionActionMockRecorder { } // Configure mocks base method. -func (m *MockReactionAction) Configure(arg0 gologger.Logger, arg1 mautrixcl.Client, arg2 messenger.Messenger, arg3 database.Service, arg4 database0.Service, arg5 *BridgeServices) { +func (m *MockReactionAction) Configure(arg0 *slog.Logger, arg1 mautrixcl.Client, arg2 messenger.Messenger, arg3 database.Service, arg4 database0.Service, arg5 *BridgeServices) { m.ctrl.T.Helper() m.ctrl.Call(m, "Configure", arg0, arg1, arg2, arg3, arg4, arg5) } diff --git a/internal/connectors/matrix/reaction_handler.go b/internal/connectors/matrix/reaction_handler.go index bf0ea501..6b12848a 100644 --- a/internal/connectors/matrix/reaction_handler.go +++ b/internal/connectors/matrix/reaction_handler.go @@ -18,12 +18,12 @@ type ReactionEvent struct { } func (service *service) ReactionEventHandler(_ mautrix.EventSource, evt *event.Event) { - logger := service.logger.WithFields(map[string]any{ - "sender": evt.Sender, - "room": evt.RoomID, - "event_timestamp": evt.Timestamp, - }) - logger.Debugf("new reaction received") + logger := service.logger.With( + "matrix.sender", evt.Sender, + "matrix.room.id", evt.RoomID, + "matrix.event.timestamp", evt.Timestamp, + ) + logger.Debug("new reaction received") // Do not answer our own and old messages if evt.Sender.String() == service.botname || evt.Timestamp/1000 <= service.lastMessageFrom.Unix() { @@ -32,7 +32,7 @@ func (service *service) ReactionEventHandler(_ mautrix.EventSource, evt *event.E room, err := service.matrixDatabase.GetRoomByRoomID(string(evt.RoomID)) if err != nil { - logger.Debugf("do not know room, ignoring message") + logger.Debug("ignoring reaction", "reason", "unknown room") return } @@ -45,36 +45,37 @@ func (service *service) ReactionEventHandler(_ mautrix.EventSource, evt *event.E } } if !isUserKnown { - logger.Debugf("do not know user, ignoring message") + logger.Debug("ignoring reaction", "reason", "unknown user") return } content, ok := evt.Content.Parsed.(*event.ReactionEventContent) if !ok { - logger.Infof("Event is not a reaction event. Can not handle it.") + logger.Info("ignoring reaction", "reason", "not a reaction event") return } if content.RelatesTo.EventID.String() == "" { - logger.Infof("Reaction with no relating message. Can not handle that.") + logger.Info("ignoring reaction", "reason", "no related event") return } message, err := service.matrixDatabase.GetMessageByID(content.RelatesTo.EventID.String()) if err != nil { - logger.Infof("Do not know the message related to the reaction.") + logger.Info("ignoring reaction", "reason", "unknown related message") return } if message.Room.RoomID != room.RoomID { // Should never happen. - logger.Infof("Ignore reaction from room %s referring to event from room %s.", message.Room.RoomID, room.RoomID) + logger.Info("ignoring reaction", "reason", "message from different room than reaction", + "matrix.message.room.id", message.Room.RoomID, "matrix.reaction.room.id", room.RoomID) return } reactionEvent, err := service.parseReactionEvent(evt, room) if err != nil { - logger.Errorf("Can not parse reaction event: %s", err.Error()) + logger.Error("failed to parse reaction event", "error", err) return } @@ -88,7 +89,7 @@ func (service *service) ReactionEventHandler(_ mautrix.EventSource, evt *event.E } } - logger.Infof("No action found matching key %s", content.RelatesTo.Key) + logger.Info("ignoring reaction", "reason", "unknown reaction", "matrix.reaction.key", content.RelatesTo.Key) } func (service *service) parseReactionEvent(evt *event.Event, room *matrixdb.MatrixRoom) (*ReactionEvent, error) { diff --git a/internal/connectors/matrix/reply_action_mock.go b/internal/connectors/matrix/reply_action_mock.go index 149f4d96..6264036d 100644 --- a/internal/connectors/matrix/reply_action_mock.go +++ b/internal/connectors/matrix/reply_action_mock.go @@ -5,10 +5,10 @@ package matrix import ( + slog "log/slog" reflect "reflect" regexp "regexp" - gologger "github.com/CubicrootXYZ/gologger" database "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" mautrixcl "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/mautrixcl" messenger "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/messenger" @@ -40,7 +40,7 @@ func (m *MockReplyAction) EXPECT() *MockReplyActionMockRecorder { } // Configure mocks base method. -func (m *MockReplyAction) Configure(arg0 gologger.Logger, arg1 mautrixcl.Client, arg2 messenger.Messenger, arg3 database.Service, arg4 database0.Service, arg5 *BridgeServices) { +func (m *MockReplyAction) Configure(arg0 *slog.Logger, arg1 mautrixcl.Client, arg2 messenger.Messenger, arg3 database.Service, arg4 database0.Service, arg5 *BridgeServices) { m.ctrl.T.Helper() m.ctrl.Call(m, "Configure", arg0, arg1, arg2, arg3, arg4, arg5) } diff --git a/internal/connectors/matrix/send_reminders.go b/internal/connectors/matrix/send_reminders.go index bbe642ee..e24117e1 100644 --- a/internal/connectors/matrix/send_reminders.go +++ b/internal/connectors/matrix/send_reminders.go @@ -18,7 +18,7 @@ func (service *service) SendReminder(event *daemon.Event, output *daemon.Output) originalMessage, err := service.matrixDatabase.GetEventMessageByOutputAndEvent(event.ID, output.OutputID, output.OutputType) if err != nil { - service.logger.Err(err) + service.logger.Error("failed to get event message", "error", err) originalMessage = nil } @@ -51,7 +51,7 @@ func (service *service) SendReminder(event *daemon.Event, output *daemon.Output) } _, err = service.matrixDatabase.NewMessage(dbMsg) if err != nil { - service.logger.Errorf("failed to save message to database: %v", err) + service.logger.Error("failed to save message to database", "error", err) } reactions := ReminderReactions @@ -66,7 +66,7 @@ func (service *service) SendReminder(event *daemon.Event, output *daemon.Output) MessageExternalIdentifier: resp.ExternalIdentifier, }) if err != nil { - service.logger.Errorf("failed to send '%s' reaction: %s", reaction, err.Error()) + service.logger.Error("failed to send reaction", "matrix.reaction", reaction, "error", err) continue } } @@ -104,7 +104,7 @@ func (service *service) SendDailyReminder(reminder *daemon.DailyReminder, output } _, err = service.matrixDatabase.NewMessage(dbMsg) if err != nil { - service.logger.Errorf("failed to save message to database: %v", err) + service.logger.Error("failed to save message to database", "error", err) } return nil diff --git a/internal/connectors/matrix/service.go b/internal/connectors/matrix/service.go index 561633ad..dd40fc69 100644 --- a/internal/connectors/matrix/service.go +++ b/internal/connectors/matrix/service.go @@ -2,10 +2,10 @@ package matrix import ( "errors" + "log/slog" "regexp" "time" - "github.com/CubicrootXYZ/gologger" icaldb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/ical/database" matrixdb "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/database" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/connectors/matrix/format" @@ -18,7 +18,7 @@ import ( type service struct { config *Config - logger gologger.Logger + logger *slog.Logger database database.Service matrixDatabase matrixdb.Service messenger messenger.Messenger @@ -35,7 +35,7 @@ type MessageAction interface { Selector() *regexp.Regexp Name() string HandleEvent(event *MessageEvent) - Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) + Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) } //go:generate mockgen -destination=reply_action_mock.go -package=matrix . ReplyAction @@ -45,7 +45,7 @@ type ReplyAction interface { Selector() *regexp.Regexp Name() string HandleEvent(event *MessageEvent, replyToMessage *matrixdb.MatrixMessage) - Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) + Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) } //go:generate mockgen -destination=reaction_action_mock.go -package=matrix . ReactionAction @@ -55,7 +55,7 @@ type ReactionAction interface { Selector() []string Name() string HandleEvent(event *ReactionEvent, reactionToMessage *matrixdb.MatrixMessage) - Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) + Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) } // Config holds information for the matrix connector. @@ -92,8 +92,8 @@ type BridgeServiceICal interface { } // New sets up a new matrix connector. -func New(config *Config, database database.Service, matrixDB matrixdb.Service, logger gologger.Logger) (Service, error) { - logger.Debugf("setting up matrix connector ...") +func New(config *Config, database database.Service, matrixDB matrixdb.Service, logger *slog.Logger) (Service, error) { + logger.Debug("setting up matrix connector") service := &service{ config: config, @@ -105,7 +105,7 @@ func New(config *Config, database database.Service, matrixDB matrixdb.Service, l err := service.setupMautrixClient() if err != nil { - service.logger.Err(err) + service.logger.Error("failed to setup mautrix client", "error", err) return nil, err } @@ -118,7 +118,7 @@ func New(config *Config, database database.Service, matrixDB matrixdb.Service, l service.setLastMessage() - logger.Debugf("matrix connector setup finished") + logger.Debug("matrix connector setup finished") return service, nil } @@ -138,7 +138,7 @@ func (service *service) setLastMessage() { func (service *service) setupActions() { // Collect all actions and inject dependencies. actions := []interface { - Configure(logger gologger.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) + Configure(logger *slog.Logger, client mautrixcl.Client, messenger messenger.Messenger, matrixDB matrixdb.Service, db database.Service, bridgeServices *BridgeServices) Name() string }{ service.config.DefaultMessageAction, @@ -157,7 +157,7 @@ func (service *service) setupActions() { for _, action := range actions { action.Configure( - service.logger.WithField("component", "action-"+action.Name()), + service.logger.With("component", "action-"+action.Name()), service.client, service.messenger, service.matrixDatabase, @@ -168,7 +168,7 @@ func (service *service) setupActions() { } func (service *service) setupMautrixClient() error { - service.logger.Debugf("setting up mautrix client ...") + service.logger.Debug("setting up mautrix client") matrixClient, err := mautrix.NewClient(service.config.Homeserver, "", "") if err != nil { @@ -185,7 +185,7 @@ func (service *service) setupMautrixClient() error { StoreCredentials: true, }) - service.logger.Debugf("matrix client setup finished") + service.logger.Debug("mautrix client setup finished") return err } @@ -193,7 +193,7 @@ func (service *service) setupMessenger() error { config := &messenger.Config{} messenger, err := messenger.NewMessenger(config, service.matrixDatabase, service.client, - service.logger.WithField("component", "matrix-messenger")) + service.logger.With("component", "matrix-messenger")) if err != nil { return err } @@ -206,16 +206,16 @@ func (service *service) setupMessenger() error { // Start starts the services asynchronous processes. // This method will block until stopped. func (service *service) Start() error { - service.logger.Debugf("starting matrix connector") + service.logger.Debug("starting matrix connector") err := service.startListener() - service.logger.Debugf("matrix connector stopped") + service.logger.Debug("matrix connector stopped") return err } // Stop stops the services asynchronous processes. // This method will not block, wait for Stop() to return. func (service *service) Stop() error { - service.logger.Debugf("stopping matrix connector ...") + service.logger.Debug("stopping matrix connector ...") service.client.StopSync() return nil } diff --git a/internal/connectors/matrix/state_handler.go b/internal/connectors/matrix/state_handler.go index 1e6742ba..09239298 100644 --- a/internal/connectors/matrix/state_handler.go +++ b/internal/connectors/matrix/state_handler.go @@ -14,12 +14,12 @@ import ( // EventStateHandler handles state events from matrix. func (service *service) EventStateHandler(_ mautrix.EventSource, evt *event.Event) { - logger := service.logger.WithFields(map[string]any{ - "sender": evt.Sender, - "room": evt.RoomID, - "event_timestamp": evt.Timestamp, - }) - logger.Debugf("new state event") + logger := service.logger.With( + "matrix.sender", evt.Sender, + "matrix.room", evt.RoomID, + "matrix.event_timestamp", evt.Timestamp, + ) + logger.Debug("new state event") // Ignore old events or events from the bot itself if evt.Sender.String() == service.botname || evt.Timestamp/1000 <= service.lastMessageFrom.Unix() { @@ -28,7 +28,7 @@ func (service *service) EventStateHandler(_ mautrix.EventSource, evt *event.Even content, ok := evt.Content.Parsed.(*event.MemberEventContent) if !ok { - logger.Infof("Event is not a member event. Can not handle it.") + logger.Info("cannot handle event", "reason", "not a member event") return } @@ -37,7 +37,7 @@ func (service *service) EventStateHandler(_ mautrix.EventSource, evt *event.Even if err == nil { return } else if !errors.Is(err, matrixdb.ErrNotFound) { - logger.Err(err) + logger.Error("failed to get event", "error", err) return } @@ -45,15 +45,15 @@ func (service *service) EventStateHandler(_ mautrix.EventSource, evt *event.Even case event.MembershipInvite, event.MembershipJoin: err := service.handleInvite(evt, content) if err != nil { - logger.Errorf("Failed to handle membership invite with: " + err.Error()) + logger.Error("failed to handle state event", "matrix.event.membership", "invite/join", "error", err) } case event.MembershipLeave, event.MembershipBan: err := service.handleLeave(evt) if err != nil { - logger.Errorf("Failed to handle membership leave with: " + err.Error()) + logger.Error("failed to handle state event", "matrix.event.membership", "leave/ban", "error", err) } default: - logger.Infof("No handling of this event as Membership %s is unknown.", content.Membership) + logger.Info("cannot handle state event", "reason", "unknown membership type", "event.membership", content.Membership) } } @@ -64,7 +64,7 @@ func (service *service) handleInvite(evt *event.Event, content *event.MemberEven } if declineInvites && !service.userInWhitelist(evt.Sender.String()) { - service.logger.Debugf(evt.Sender.String() + " ignored bot reached max users or invites are disallowed") + service.logger.Debug("invite ignored", "reason", "disabled/not whitelisted", "matrix.user", evt.Sender.String()) return nil } @@ -77,7 +77,7 @@ func (service *service) handleInvite(evt *event.Event, content *event.MemberEven } if user != nil && user.Blocked { - service.logger.Debugf("user '%s' is blocked - ignoring", evt.Sender.String()) + service.logger.Debug("invite ignored", "reason", "blocked", "matrix.user", evt.Sender.String()) return nil } @@ -94,7 +94,7 @@ func (service *service) handleInvite(evt *event.Event, content *event.MemberEven // TODO for further testing service.client needs to be mocked. _, err = service.client.JoinRoom(evt.RoomID.String(), "", nil) if err != nil { - service.logger.Errorf("Failed joining channel %s with: %s", evt.RoomID.String(), err.Error()) + service.logger.Error("failed to join channel", "error", err, "matrix.room.id", evt.RoomID.String()) return err } @@ -133,7 +133,7 @@ func (service *service) handleInvite(evt *event.Event, content *event.MemberEven err = service.setupNewChannel(room, user) if err != nil { - service.logger.Errorf("failed to setup new channel: %s", err.Error()) + service.logger.Error("failed to setup new channel", "error", err) return err } @@ -186,7 +186,7 @@ func (service *service) sendWelcomeMessage(room *matrixdb.MatrixRoom, user *matr room.RoomID, )) if err != nil { - service.logger.Infof("failed to send message: " + err.Error()) + service.logger.Info("failed to send message", "error", err.Error()) return } @@ -201,7 +201,7 @@ func (service *service) sendWelcomeMessage(room *matrixdb.MatrixRoom, user *matr Incoming: false, }) if err != nil { - service.logger.Errorf("failed saving message into database: " + err.Error()) + service.logger.Error("failed saving message to database", "error", err.Error()) } } @@ -264,10 +264,7 @@ func (service *service) handleLeave(evt *event.Event) error { if time.Unix(evt.Timestamp/1000, 0).Sub(room.CreatedAt) < 0 { // Got invited to room after this event. Ignore this event. - service.logger.Infof( - "ignoring leave/ban for room '%s' as got invited afterwards again", - room.RoomID, - ) + service.logger.Info("leave ignored", "reason", "got invited again", "matrix.room.id", room.RoomID) return nil } @@ -278,7 +275,7 @@ func (service *service) handleLeave(evt *event.Event) error { err = service.removeFromChannel(room) if err != nil { - service.logger.Errorf("failed to remove room from channel: %s", err.Error()) + service.logger.Error("failed to remove room from channel", "error", err) return err } @@ -286,7 +283,7 @@ func (service *service) handleLeave(evt *event.Event) error { _, err = service.client.LeaveRoom(evt.RoomID) if err != nil { // Fire and forget, we might already be banned - service.logger.Err(err) + service.logger.Error("failed to leave room", "error", err) } return nil @@ -313,7 +310,7 @@ func (service *service) removeRoom(room *matrixdb.MatrixRoom) error { return err } - service.logger.Infof("found %d dangling matrix users, deleted them", cnt) + service.logger.Info("deleted dangling matrix users", "count", cnt) return nil } diff --git a/internal/coreapi/channels_handler.go b/internal/coreapi/channels_handler.go index 7a2218fb..5a736fbb 100644 --- a/internal/coreapi/channels_handler.go +++ b/internal/coreapi/channels_handler.go @@ -54,7 +54,7 @@ func channelsToResponse(channelsIn []database.Channel) []Channel { func (api *coreAPI) listChannelsHandler(ctx *gin.Context) { channels, err := api.config.Database.GetChannels() if err != nil { - api.logger.Err(err) + api.logger.Error("failed to list channels", "error", err) response.AbortWithInternalServerError(ctx) return } diff --git a/internal/coreapi/core_api.go b/internal/coreapi/core_api.go index 392af2b2..8741997e 100644 --- a/internal/coreapi/core_api.go +++ b/internal/coreapi/core_api.go @@ -1,14 +1,15 @@ package coreapi import ( - "github.com/CubicrootXYZ/gologger" + "log/slog" + "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" "github.com/gin-gonic/gin" ) type coreAPI struct { config *Config - logger gologger.Logger + logger *slog.Logger } // Config holds the configuration for the core API. @@ -19,7 +20,7 @@ type Config struct { // New assembles a new core API. // Core API uses the /core path prefix. -func New(config *Config, logger gologger.Logger) CoreAPI { +func New(config *Config, logger *slog.Logger) CoreAPI { return &coreAPI{ config: config, logger: logger, diff --git a/internal/coreapi/core_api_test.go b/internal/coreapi/core_api_test.go index a37e236a..c22568fd 100644 --- a/internal/coreapi/core_api_test.go +++ b/internal/coreapi/core_api_test.go @@ -1,10 +1,10 @@ package coreapi_test import ( + "log/slog" "net/http/httptest" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/api/middleware" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/coreapi" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -13,13 +13,12 @@ import ( ) func testCoreAPI(ctrl *gomock.Controller) (*httptest.Server, *database.MockService) { - logger := gologger.New(gologger.LogLevelDebug, 0) db := database.NewMockService(ctrl) api := coreapi.New(&coreapi.Config{ Database: db, DefaultAuthProvider: middleware.APIKeyAuth("123"), - }, logger) + }, slog.Default()) r := gin.New() err := api.RegisterRoutes(r) diff --git a/internal/daemon/daily_reminders.go b/internal/daemon/daily_reminders.go index e9ab97ec..5177c734 100644 --- a/internal/daemon/daily_reminders.go +++ b/internal/daemon/daily_reminders.go @@ -13,8 +13,8 @@ func (service *service) sendOutDailyReminders() error { } service.logger. - WithField("channels", len(channels)). - Debugf("checking channels for daily reminder") + With("channels", len(channels)). + Debug("checking channels for daily reminder") eventsAfter := time.Now() eventsBefore := eventsAfter.Add(time.Hour*24 + time.Second) @@ -22,8 +22,9 @@ func (service *service) sendOutDailyReminders() error { for _, channel := range channels { if !isDailyReminderTimeReached(channel) { service.logger. - WithField("channel", channel.ID). - Debugf("no daily reminder send out - reminder time not reached") + Debug("no daily reminder send out", + "channel.id", channel.ID, + "reason", "reminder time not reached") continue } @@ -33,34 +34,35 @@ func (service *service) sendOutDailyReminders() error { EventsBefore: &eventsBefore, }) if err != nil { - service.logger.Err(err) + service.logger.Error("failed to list events", "error", err) continue } for _, output := range channel.Outputs { if isDailyReminderSentToday(&output) { service.logger. - WithField("channel", channel.ID). - Debugf("no daily reminder send out - already done") + Debug("no daily reminder send out", + "channel.id", channel.ID, + "reason", "already done") continue } outputService, ok := service.config.OutputServices[output.OutputType] if !ok { - service.logger.Errorf("missing output service for type: %s", output.OutputType) + service.logger.Error("unknown output type", "output.type", output.OutputType) continue } - service.logger.WithFields(map[string]any{ - "events": len(events), - "output_type": output.OutputType, - "output_id": output.OutputID, - "daily_reminder_time": channel.DailyReminder, - }).Debugf("sending out daily reminder") + service.logger.With( + "events", len(events), + "output.type", output.OutputType, + "output.id", output.OutputID, + "daily_reminder_time", channel.DailyReminder, + ).Debug("sending out daily reminder") err := outputService.SendDailyReminder(dailyReminderFromDatabase(events), outputFromDatabase(&output)) if err != nil { - service.logger.Err(err) + service.logger.Error("failed to send out daily reminder", "error", err) continue } @@ -68,7 +70,7 @@ func (service *service) sendOutDailyReminders() error { output.LastDailyReminder = &now _, err = service.database.UpdateOutput(&output) if err != nil { - service.logger.Err(err) + service.logger.Error("failed to update output", "error", err) } } } diff --git a/internal/daemon/events.go b/internal/daemon/events.go index 35f109a3..0e53adb9 100644 --- a/internal/daemon/events.go +++ b/internal/daemon/events.go @@ -12,14 +12,17 @@ func (service *service) sendOutEvents() error { outputService, ok := service.config.OutputServices[event.Channel.Outputs[j].OutputType] if !ok { - service.logger.Errorf("missing output service for type: %s", event.Channel.Outputs[j].OutputType) + service.logger.Error("unknown output type", "output.type", event.Channel.Outputs[j].OutputType) continue } err = outputService.SendReminder(eventFromDatabase(&event), outputFromDatabase(&event.Channel.Outputs[j])) if err != nil { eventSuccess = false - service.logger.Err(err) + service.logger.Error("failed to send reminder to output", + "error", err, + "output.id", event.Channel.Outputs[j].OutputID, + "output.type", event.Channel.Outputs[j].OutputType) continue } } @@ -41,7 +44,7 @@ func (service *service) sendOutEvents() error { _, err = service.database.UpdateEvent(&event) if err != nil { - service.logger.Errorf("failed updating event after sending reminder: %w", err) + service.logger.Error("failed updating event after sending reminder", "error", err) continue } } diff --git a/internal/daemon/events_test.go b/internal/daemon/events_test.go index 77764915..e5498aad 100644 --- a/internal/daemon/events_test.go +++ b/internal/daemon/events_test.go @@ -2,10 +2,10 @@ package daemon_test import ( "errors" + "log/slog" "testing" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/daemon" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/daemon/mocks" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" @@ -23,7 +23,7 @@ func testDaemon(ctrl *gomock.Controller, events, daily bool) (daemon.Service, *d }, EventsInterval: intervalFromBool(events), DailyReminderInterval: intervalFromBool(daily), - }, db, gologger.New(gologger.LogLevelDebug, 0)), db, outputService + }, db, slog.Default()), db, outputService } func intervalFromBool(b bool) time.Duration { diff --git a/internal/daemon/service.go b/internal/daemon/service.go index 9d3aa31c..7c5cddba 100644 --- a/internal/daemon/service.go +++ b/internal/daemon/service.go @@ -1,17 +1,17 @@ package daemon import ( + "log/slog" "sync" "time" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" ) type service struct { config *Config database database.Service - logger gologger.Logger + logger *slog.Logger done chan interface{} daemonWG *sync.WaitGroup @@ -32,7 +32,7 @@ type Config struct { } // New assembles a new service. -func New(config *Config, database database.Service, logger gologger.Logger) Service { +func New(config *Config, database database.Service, logger *slog.Logger) Service { return &service{ config: config, database: database, @@ -60,13 +60,13 @@ func (service *service) startEventDaemon() { for { select { case <-eventsTicker.C: - service.logger.Debugf("sending out events ...") + service.logger.Debug("sending out events ...") err := service.sendOutEvents() if err != nil { - service.logger.Err(err) + service.logger.Error("failed to send out events", "error", err) } case <-service.done: - service.logger.Debugf("event daemon stopped") + service.logger.Debug("event daemon stopped") service.daemonWG.Done() return } @@ -82,10 +82,10 @@ func (service *service) startDailyReminderDaemon() { case <-dailyReminderTicker.C: err := service.sendOutDailyReminders() if err != nil { - service.logger.Err(err) + service.logger.Error("failed to send out daily reminders", "error", err) } case <-service.done: - service.logger.Debugf("event daemon stopped") + service.logger.Debug("event daemon stopped") service.daemonWG.Done() return } @@ -95,7 +95,7 @@ func (service *service) startDailyReminderDaemon() { // Stops shuts down the service in an unblocking way. // Start() will return once the daemon is stopped. func (service *service) Stop() error { - service.logger.Debugf("stopping daemon ...") + service.logger.Debug("stopping daemon ...") close(service.done) return nil diff --git a/internal/database/service.go b/internal/database/service.go index b7026b27..6d8eca7b 100644 --- a/internal/database/service.go +++ b/internal/database/service.go @@ -1,7 +1,8 @@ package database import ( - "github.com/CubicrootXYZ/gologger" + "log/slog" + "github.com/CubicrootXYZ/gormlogger" "gorm.io/driver/mysql" "gorm.io/gorm" @@ -9,7 +10,7 @@ import ( type service struct { db *gorm.DB - logger gologger.Logger + logger *slog.Logger config *Config } @@ -35,8 +36,8 @@ type Config struct { } // NewService assembles a new database service. -func NewService(config *Config, logger gologger.Logger) (Service, error) { - logger.Debugf("setting up database ...") +func NewService(config *Config, logger *slog.Logger) (Service, error) { + logger.Debug("setting up database") if config == nil { return nil, ErrInvalidConfig @@ -57,13 +58,13 @@ func NewService(config *Config, logger gologger.Logger) (Service, error) { logger: logger, } - logger.Debugf("migrating database ...") + logger.Debug("migrating database") err = service.migrate() if err != nil { return nil, err } - logger.Debugf("database setup finished") + logger.Debug("database setup finished") return service, nil } @@ -105,11 +106,11 @@ func (service *service) commit() error { } func (service *service) rollbackWithError(err error) error { - service.logger.Infof("rollbacking transaction due to error: %v", err) + service.logger.Info("rollback transaction", "error", err) err2 := service.db.Rollback().Error if err2 != nil { - service.logger.Errorf("rollbacking failed with: %v", err2) + service.logger.Error("rollback failed", "error", err2, "original_error", err) } return err diff --git a/internal/database/service_test.go b/internal/database/service_test.go index 71d8c47b..3cd87d14 100644 --- a/internal/database/service_test.go +++ b/internal/database/service_test.go @@ -1,17 +1,17 @@ package database_test import ( + "log/slog" "os" "testing" - "github.com/CubicrootXYZ/gologger" "github.com/CubicrootXYZ/matrix-reminder-and-calendar-bot/internal/database" "github.com/stretchr/testify/require" "gorm.io/driver/mysql" "gorm.io/gorm" ) -var logger gologger.Logger +var logger *slog.Logger var service database.Service var gormDB *gorm.DB @@ -45,8 +45,8 @@ func getGormDB() *gorm.DB { return db } -func getLogger() gologger.Logger { - return gologger.New(gologger.LogLevelDebug, 0) +func getLogger() *slog.Logger { + return slog.New(slog.NewTextHandler(os.Stdout, nil)) } func TestMain(m *testing.M) {