[core] Configure logger for mysql driver

Signed-off-by: Knut Ahlers <knut@ahlers.me>
This commit is contained in:
Knut Ahlers 2022-10-29 15:01:01 +02:00
parent 064c7432ed
commit 231704f8b3
Signed by: luzifer
GPG key ID: D91C3E91E4CAD6F5
2 changed files with 9 additions and 10 deletions

View file

@ -9,6 +9,7 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/glebarez/sqlite" "github.com/glebarez/sqlite"
mysqlDriver "github.com/go-sql-driver/mysql"
"gorm.io/driver/mysql" "gorm.io/driver/mysql"
"gorm.io/driver/postgres" "gorm.io/driver/postgres"
"gorm.io/gorm" "gorm.io/gorm"
@ -35,6 +36,7 @@ func New(driverName, connString, encryptionSecret string) (Connector, error) {
switch driverName { switch driverName {
case "mysql": case "mysql":
mysqlDriver.SetLogger(newLogrusLogWriterWithLevel(logrus.ErrorLevel, driverName))
innerDB = mysql.Open(connString) innerDB = mysql.Open(connString)
case "postgres": case "postgres":
@ -53,7 +55,7 @@ func New(driverName, connString, encryptionSecret string) (Connector, error) {
} }
db, err := gorm.Open(innerDB, &gorm.Config{ db, err := gorm.Open(innerDB, &gorm.Config{
Logger: gormLogger(), Logger: logger.New(newLogrusLogWriterWithLevel(logrus.TraceLevel, driverName), logger.Config{}),
}) })
if err != nil { if err != nil {
return nil, errors.Wrap(err, "connecting database") 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") 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) { func patchSQLiteConnString(connString string) (string, error) {
u, err := url.Parse(connString) u, err := url.Parse(connString)
if err != nil { if err != nil {

View file

@ -11,11 +11,15 @@ type (
logWriter struct{ io.Writer } logWriter struct{ io.Writer }
) )
func newLogrusLogWriterWithLevel(level logrus.Level) logWriter { func newLogrusLogWriterWithLevel(level logrus.Level, dbDriver string) logWriter {
writer := logrus.StandardLogger().WriterLevel(level) writer := logrus.WithField("database", dbDriver).WriterLevel(level)
return logWriter{writer} return logWriter{writer}
} }
func (l logWriter) Print(a ...any) {
fmt.Fprint(l.Writer, a...)
}
func (l logWriter) Printf(format string, a ...any) { func (l logWriter) Printf(format string, a ...any) {
fmt.Fprintf(l.Writer, format, a...) fmt.Fprintf(l.Writer, format, a...)
} }