From c3ea735c0f03a0827a8e753a5b5adf6e31f4c925 Mon Sep 17 00:00:00 2001 From: Gabriel Arakaki Giovanini Date: Tue, 24 Oct 2023 19:12:52 +0200 Subject: feat: Migrate from logrus to slog --- pkg/ext/gorm_logger.go | 28 ++++++++++--------------- pkg/ext/middleware.go | 43 +++++++++++++++++++++------------------ pkg/worker/list_processor.go | 39 ++++++++++++++++++++++------------- pkg/worker/list_processor_test.go | 11 +++++----- 4 files changed, 64 insertions(+), 57 deletions(-) (limited to 'pkg') diff --git a/pkg/ext/gorm_logger.go b/pkg/ext/gorm_logger.go index bfbbb1e..f0ab592 100644 --- a/pkg/ext/gorm_logger.go +++ b/pkg/ext/gorm_logger.go @@ -3,15 +3,15 @@ package ext import ( "context" "fmt" + "log/slog" "time" - "github.com/sirupsen/logrus" "gorm.io/gorm/logger" "gorm.io/gorm/utils" ) type Log struct { - logrus *logrus.Entry + logger *slog.Logger } func getFullMsg(msg string, data ...interface{}) string { @@ -24,35 +24,29 @@ func (self *Log) LogMode(_ logger.LogLevel) logger.Interface { func (self *Log) Info(ctx context.Context, msg string, data ...interface{}) { fullMsg := getFullMsg(msg, data) - self.logrus. - WithContext(ctx). - Info(fullMsg) + self.logger.InfoContext(ctx, fullMsg) } func (self *Log) Warn(ctx context.Context, msg string, data ...interface{}) { fullMsg := getFullMsg(msg, data) - self.logrus. - WithContext(ctx). - Warn(fullMsg) + self.logger. + WarnContext(ctx, fullMsg) } func (self *Log) Error(ctx context.Context, msg string, data ...interface{}) { fullMsg := getFullMsg(msg, data) - self.logrus. - WithContext(ctx). - Error(fullMsg) + self.logger. + ErrorContext(ctx, fullMsg) } func (self *Log) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), _ error) { elapsed := time.Since(begin) sql, _ := fc() - self.logrus. - WithContext(ctx). - WithField("time", elapsed). - Printf(sql) + self.logger. + InfoContext(ctx, sql, slog.Duration("elapsed", elapsed)) } -func Wraplog(log *logrus.Entry) *Log { +func Wraplog(log *slog.Logger) *Log { return &Log{ - logrus: log, + logger: log, } } diff --git a/pkg/ext/middleware.go b/pkg/ext/middleware.go index 6a94c4f..38bacca 100644 --- a/pkg/ext/middleware.go +++ b/pkg/ext/middleware.go @@ -4,11 +4,10 @@ import ( "context" "encoding/base64" "errors" + "log/slog" "net/http" "time" - "github.com/sirupsen/logrus" - "git.sr.ht/~gabrielgio/img/pkg/database/repository" "git.sr.ht/~gabrielgio/img/pkg/service" ) @@ -24,7 +23,7 @@ type ( User string LogMiddleware struct { - entry *logrus.Entry + logger *slog.Logger } ) @@ -32,9 +31,9 @@ const ( UserKey User = "user" ) -func NewLogMiddleare(log *logrus.Entry) *LogMiddleware { +func NewLogMiddleare(log *slog.Logger) *LogMiddleware { return &LogMiddleware{ - entry: log, + logger: log, } } @@ -43,27 +42,29 @@ func (l *LogMiddleware) HTTP(next http.HandlerFunc) http.HandlerFunc { start := time.Now() next(w, r) elapsed := time.Since(start) - l.entry. - WithField("time", elapsed). - WithField("path", r.URL.Path). - Info(r.Method) + l.logger.Info( + r.Method, + slog.Duration("elapsed", elapsed), + slog.String("path", r.URL.Path), + ) + } } type AuthMiddleware struct { key []byte - entry *logrus.Entry + logger *slog.Logger userRepository repository.UserRepository } func NewAuthMiddleware( key []byte, - log *logrus.Entry, + logger *slog.Logger, userRepository repository.UserRepository, ) *AuthMiddleware { return &AuthMiddleware{ key: key, - entry: log.WithField("context", "auth"), + logger: logger, userRepository: userRepository, } } @@ -79,35 +80,37 @@ func (a *AuthMiddleware) LoggedIn(next http.HandlerFunc) http.HandlerFunc { redirectLogin := "/login?redirect=" + path authBase64, err := r.Cookie("auth") if errors.Is(err, http.ErrNoCookie) { - a.entry.Info("No auth provided") + a.logger.Info("No auth provided") http.Redirect(w, r, redirectLogin, http.StatusTemporaryRedirect) return } auth, err := base64.StdEncoding.DecodeString(authBase64.Value) if err != nil { - a.entry.Error(err) + a.logger.Error(err.Error()) return } token, err := service.ReadToken(auth, a.key) if err != nil { - a.entry.Error(err) + a.logger.Error(err.Error()) http.Redirect(w, r, redirectLogin, http.StatusTemporaryRedirect) return } user, err := a.userRepository.Get(r.Context(), token.UserID) if err != nil { - a.entry.Error(err) + a.logger.Error(err.Error()) return } r = r.WithContext(context.WithValue(r.Context(), UserKey, user)) - a.entry. - WithField("userID", token.UserID). - WithField("username", token.Username). - Info("user recognized") + a.logger. + Info( + "user recognized", + slog.Uint64("userid", uint64(token.UserID)), + slog.String("username", token.Username), + ) next(w, r) } } diff --git a/pkg/worker/list_processor.go b/pkg/worker/list_processor.go index ea6b453..c4c3781 100644 --- a/pkg/worker/list_processor.go +++ b/pkg/worker/list_processor.go @@ -3,9 +3,8 @@ package worker import ( "context" "errors" + "log/slog" "sync" - - "github.com/sirupsen/logrus" ) type ( @@ -27,19 +26,19 @@ type ( chanProcessorTask[T any] struct { chanProcessor ChanProcessor[T] - logrus *logrus.Entry + logger *slog.Logger scheduler *Scheduler } batchProcessorTask[T any] struct { batchProcessor ListProcessor[T] - logrus *logrus.Entry + logger *slog.Logger scheduler *Scheduler } serialProcessorTask[T any] struct { batchProcessor ListProcessor[T] - logrus *logrus.Entry + logger *slog.Logger scheduler *Scheduler } ) @@ -47,36 +46,36 @@ type ( func NewTaskFromBatchProcessor[T any]( batchProcessor ListProcessor[T], scheduler *Scheduler, - logrus *logrus.Entry, + logger *slog.Logger, ) Task { return &batchProcessorTask[T]{ batchProcessor: batchProcessor, scheduler: scheduler, - logrus: logrus, + logger: logger, } } func NewTaskFromSerialProcessor[T any]( batchProcessor ListProcessor[T], scheduler *Scheduler, - logrus *logrus.Entry, + logger *slog.Logger, ) Task { return &serialProcessorTask[T]{ batchProcessor: batchProcessor, scheduler: scheduler, - logrus: logrus, + logger: logger, } } func NewTaskFromChanProcessor[T any]( chanProcessor ChanProcessor[T], scheduler *Scheduler, - logrus *logrus.Entry, + logger *slog.Logger, ) Task { return &chanProcessorTask[T]{ chanProcessor: chanProcessor, scheduler: scheduler, - logrus: logrus, + logger: logger, } } @@ -111,7 +110,10 @@ func (l *batchProcessorTask[T]) Start(ctx context.Context) error { defer l.scheduler.Return() defer wg.Done() if err := l.batchProcessor.Process(ctx, v); err != nil && !errors.Is(err, context.Canceled) { - l.logrus.WithError(err).Error("Error processing batch") + l.logger.Error( + "Error processing batch", + slog.String("error", err.Error()), + ) if failure, ok := l.batchProcessor.(OnFail[T]); ok { failure.OnFail(ctx, v, err) } @@ -148,7 +150,10 @@ func (l *serialProcessorTask[T]) Start(ctx context.Context) error { l.scheduler.Take() if err := l.batchProcessor.Process(ctx, v); err != nil && !errors.Is(err, context.Canceled) { - l.logrus.WithError(err).Error("Error processing batch") + l.logger.Error( + "Error processing batch", + slog.String("error", err.Error()), + ) if failure, ok := l.batchProcessor.(OnFail[T]); ok { failure.OnFail(ctx, v, err) } @@ -177,7 +182,13 @@ func (l *chanProcessorTask[T]) Start(ctx context.Context) error { go func(v T) { defer l.scheduler.Return() if err := l.chanProcessor.Process(ctx, v); err != nil { - l.logrus.WithError(err).Error("Error processing chan") + l.logger.Error( + "Error processing batch", + slog.String("error", err.Error()), + ) + if failure, ok := l.chanProcessor.(OnFail[T]); ok { + failure.OnFail(ctx, v, err) + } } }(v) } diff --git a/pkg/worker/list_processor_test.go b/pkg/worker/list_processor_test.go index abdb907..21489e8 100644 --- a/pkg/worker/list_processor_test.go +++ b/pkg/worker/list_processor_test.go @@ -5,12 +5,11 @@ package worker import ( "context" "errors" + "log/slog" "math/rand" "sync" "testing" - "github.com/sirupsen/logrus" - "git.sr.ht/~gabrielgio/img/pkg/testkit" ) @@ -27,12 +26,12 @@ type ( func TestListProcessorLimit(t *testing.T) { var ( - log = logrus.New() + log = slog.Default() scheduler = NewScheduler(1) mock = &mockCounterListProcessor{countTo: 10000} ) - worker := NewTaskFromBatchProcessor[int](mock, scheduler, log.WithField("context", "testing")) + worker := NewTaskFromBatchProcessor[int](mock, scheduler, log.With("context", "testing")) err := worker.Start(context.Background()) testkit.TestFatalError(t, "Start", err) @@ -42,12 +41,12 @@ func TestListProcessorLimit(t *testing.T) { func TestListProcessorContextCancelQuery(t *testing.T) { var ( - log = logrus.New() + log = slog.Default() scheduler = NewScheduler(1) mock = &mockContextListProcessor{} ) - worker := NewTaskFromBatchProcessor[int](mock, scheduler, log.WithField("context", "testing")) + worker := NewTaskFromBatchProcessor[int](mock, scheduler, log.With("context", "testing")) ctx, cancel := context.WithCancel(context.Background()) var wg sync.WaitGroup -- cgit v1.2.3