Skip to content

Commit

Permalink
chore: unify logger for gorm
Browse files Browse the repository at this point in the history
  • Loading branch information
dipeshdulal committed Aug 9, 2021
1 parent 3f3c48f commit a75abf8
Show file tree
Hide file tree
Showing 2 changed files with 86 additions and 18 deletions.
23 changes: 5 additions & 18 deletions lib/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@ package lib

import (
"fmt"
"log"
"os"
"time"

"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

// Database modal
Expand All @@ -17,7 +13,7 @@ type Database struct {
}

// NewDatabase creates a new database instance
func NewDatabase(env Env, zapLogger Logger) Database {
func NewDatabase(env Env, logger Logger) Database {

username := env.DBUsername
password := env.DBPassword
Expand All @@ -27,25 +23,16 @@ func NewDatabase(env Env, zapLogger Logger) Database {

url := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", username, password, host, port, dbname)

newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
SlowThreshold: time.Second,
LogLevel: logger.Info,
Colorful: true,
},
)

db, err := gorm.Open(mysql.Open(url), &gorm.Config{
Logger: newLogger,
Logger: logger.GetGormLogger(),
})

if err != nil {
zapLogger.Info("Url: ", url)
zapLogger.Panic(err)
logger.Info("Url: ", url)
logger.Panic(err)
}

zapLogger.Info("Database connection established")
logger.Info("Database connection established")

return Database{
DB: db,
Expand Down
81 changes: 81 additions & 0 deletions lib/logger.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
package lib

import (
"context"
"os"
"time"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"

gormlogger "gorm.io/gorm/logger"
)

// Logger structure
Expand All @@ -20,6 +24,11 @@ type FxLogger struct {
*Logger
}

type GormLogger struct {
*Logger
gormlogger.Config
}

var (
globalLogger *Logger
zapLogger *zap.Logger
Expand Down Expand Up @@ -55,6 +64,21 @@ func (l Logger) GetFxLogger() FxLogger {
}
}

// GetGormLogger gets the gorm framework logger
func (l Logger) GetGormLogger() *GormLogger {
logger := zapLogger.WithOptions(
zap.AddCaller(),
zap.AddCallerSkip(3),
)

return &GormLogger{
Logger: newSugaredLogger(logger),
Config: gormlogger.Config{
LogLevel: gormlogger.Info,
},
}
}

func newSugaredLogger(logger *zap.Logger) *Logger {
return &Logger{
SugaredLogger: logger.Sugar(),
Expand Down Expand Up @@ -92,3 +116,60 @@ func (l GinLogger) Write(p []byte) (n int, err error) {
func (l FxLogger) Printf(str string, args ...interface{}) {
l.Infof(str, args)
}

// GORM Framework Logger Interface Implementations
// ---- START ----

// LogMode set log mode
func (l *GormLogger) LogMode(level gormlogger.LogLevel) gormlogger.Interface {
newlogger := *l
newlogger.LogLevel = level
return &newlogger
}

// Info prints info
func (l GormLogger) Info(ctx context.Context, str string, args ...interface{}) {
if l.LogLevel >= gormlogger.Info {
l.Debugf(str, args...)
}
}

// Warn prints warn messages
func (l GormLogger) Warn(ctx context.Context, str string, args ...interface{}) {
if l.LogLevel >= gormlogger.Warn {
l.Warnf(str, args...)
}

}

// Error prints error messages
func (l GormLogger) Error(ctx context.Context, str string, args ...interface{}) {
if l.LogLevel >= gormlogger.Error {
l.Errorf(str, args...)
}
}

// Trace prints trace messages
func (l GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
if l.LogLevel <= 0 {
return
}
elapsed := time.Since(begin)
if l.LogLevel >= gormlogger.Info {
sql, rows := fc()
l.Debug("[", elapsed.Milliseconds(), " ms, ", rows, " rows] ", "sql -> ", sql)
return
}

if l.LogLevel >= gormlogger.Warn {
sql, rows := fc()
l.SugaredLogger.Warn("[", elapsed.Milliseconds(), " ms, ", rows, " rows] ", "sql -> ", sql)
return
}

if l.LogLevel >= gormlogger.Error {
sql, rows := fc()
l.SugaredLogger.Error("[", elapsed.Milliseconds(), " ms, ", rows, " rows] ", "sql -> ", sql)
return
}
}

0 comments on commit a75abf8

Please sign in to comment.