From ba191417d9a126d2338c7f5142f100e6354e99ad Mon Sep 17 00:00:00 2001 From: Aditya Thebe Date: Mon, 6 Nov 2023 16:37:04 +0545 Subject: [PATCH] fix: db log level mapping to logrus --- db.go | 15 +-------------- logger.go | 33 ++++++++++++++++++--------------- 2 files changed, 19 insertions(+), 29 deletions(-) diff --git a/db.go b/db.go index 33ecfef1..a51ac591 100644 --- a/db.go +++ b/db.go @@ -14,7 +14,6 @@ import ( "github.com/sirupsen/logrus" gormpostgres "gorm.io/driver/postgres" "gorm.io/gorm" - glogger "gorm.io/gorm/logger" ) var pool *pgxpool.Pool @@ -22,24 +21,12 @@ var pool *pgxpool.Pool var DefaultQueryTimeout = 30 * time.Second func DefaultGormConfig() *gorm.Config { - var gloggerLevel glogger.LogLevel - switch LogLevel { - case "warn": - gloggerLevel = glogger.Warn - case "error": - gloggerLevel = glogger.Error - case "info": - gloggerLevel = glogger.Info - default: - gloggerLevel = glogger.Silent - } - return &gorm.Config{ FullSaveAssociations: true, NowFunc: func() time.Time { return time.Now().UTC() }, - Logger: NewGormLogger().LogMode(gloggerLevel), + Logger: NewGormLogger(LogLevel), } } diff --git a/logger.go b/logger.go index ac5ea1a0..aa2c54c9 100644 --- a/logger.go +++ b/logger.go @@ -16,7 +16,7 @@ import ( var LogLevel string func BindFlags(flags *pflag.FlagSet) { - flags.StringVar(&LogLevel, "db-log-level", "error", "Set gorm logging level. error, warn & info") + flags.StringVar(&LogLevel, "db-log-level", "error", "Set gorm logging level. trace, debug & info") } type gormLogger struct { @@ -25,31 +25,34 @@ type gormLogger struct { IgnoreRecordNotFoundError bool } -func NewGormLogger() gLogger.Interface { - l := logrus.StandardLogger() +func NewGormLogger(level string) gLogger.Interface { + l := logrus.New() l.SetFormatter(&logrus.TextFormatter{ ForceColors: true, DisableQuote: true, }) + currentGormLogger := logger.NewLogrusLogger(l) + + switch LogLevel { + case "trace": + currentGormLogger.SetLogLevel(2) + case "debug": + currentGormLogger.SetLogLevel(1) + default: + currentGormLogger.SetLogLevel(0) + } + return &gormLogger{ SlowThreshold: time.Second, - logger: logger.NewLogrusLogger(l), + logger: currentGormLogger, } } +// Pass the log level directly to NewGormLogger func (t *gormLogger) LogMode(level gLogger.LogLevel) gLogger.Interface { - switch level { - case gLogger.Silent: - t.logger.SetLogLevel(int(logrus.FatalLevel)) - case gLogger.Error: - t.logger.SetLogLevel(int(logrus.ErrorLevel)) - case gLogger.Warn: - t.logger.SetLogLevel(int(logrus.WarnLevel)) - default: - t.logger.SetLogLevel(int(logrus.InfoLevel)) - } - + // not applicable since the mapping of gorm's loglevel to common's logger's log level + // doesn't work out well. return t }