From 231704f8b3fab46d3541207712529376cf657b64 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Sat, 29 Oct 2022 15:01:01 +0200 Subject: [PATCH] [core] Configure logger for mysql driver Signed-off-by: Knut Ahlers --- pkg/database/connector.go | 11 +++-------- pkg/database/logger.go | 8 ++++++-- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/pkg/database/connector.go b/pkg/database/connector.go index 2911e63..b79cd05 100644 --- a/pkg/database/connector.go +++ b/pkg/database/connector.go @@ -9,6 +9,7 @@ import ( "github.com/sirupsen/logrus" "github.com/glebarez/sqlite" + mysqlDriver "github.com/go-sql-driver/mysql" "gorm.io/driver/mysql" "gorm.io/driver/postgres" "gorm.io/gorm" @@ -35,6 +36,7 @@ func New(driverName, connString, encryptionSecret string) (Connector, error) { switch driverName { case "mysql": + mysqlDriver.SetLogger(newLogrusLogWriterWithLevel(logrus.ErrorLevel, driverName)) innerDB = mysql.Open(connString) case "postgres": @@ -53,7 +55,7 @@ func New(driverName, connString, encryptionSecret string) (Connector, error) { } db, err := gorm.Open(innerDB, &gorm.Config{ - Logger: gormLogger(), + Logger: logger.New(newLogrusLogWriterWithLevel(logrus.TraceLevel, driverName), logger.Config{}), }) if err != nil { return nil, errors.Wrap(err, "connecting database") @@ -85,13 +87,6 @@ func (c connector) applyCoreSchema() error { return errors.Wrap(c.db.AutoMigrate(&coreKV{}), "applying coreKV schema") } -func gormLogger() logger.Interface { - return logger.New( - newLogrusLogWriterWithLevel(logrus.TraceLevel), - logger.Config{}, - ) -} - func patchSQLiteConnString(connString string) (string, error) { u, err := url.Parse(connString) if err != nil { diff --git a/pkg/database/logger.go b/pkg/database/logger.go index f34ea14..d042056 100644 --- a/pkg/database/logger.go +++ b/pkg/database/logger.go @@ -11,11 +11,15 @@ type ( logWriter struct{ io.Writer } ) -func newLogrusLogWriterWithLevel(level logrus.Level) logWriter { - writer := logrus.StandardLogger().WriterLevel(level) +func newLogrusLogWriterWithLevel(level logrus.Level, dbDriver string) logWriter { + writer := logrus.WithField("database", dbDriver).WriterLevel(level) return logWriter{writer} } +func (l logWriter) Print(a ...any) { + fmt.Fprint(l.Writer, a...) +} + func (l logWriter) Printf(format string, a ...any) { fmt.Fprintf(l.Writer, format, a...) }