Logger

Logger

Gorm has a default logger implementation, it will print Slow SQL and happening errors by default

The logger accepts few options, you can customize it during initialization, for example:

newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
logger.Config{
SlowThreshold: time.Second, // Slow SQL threshold
LogLevel: logger.Silent, // Log level
IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
ParameterizedQueries: true, // Don't include params in the SQL log
Colorful: false, // Disable color
},
)

// Globally mode
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
Logger: newLogger,
})

// Continuous session mode
tx := db.Session(&Session{Logger: newLogger})
tx.First(&user)
tx.Model(&user).Update("Age", 18)

Log Levels

GORM defined log levels: Silent, Error, Warn, Info

db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
Logger: logger.Default.LogMode(logger.Silent),
})

Debug

Debug a single operation, change current operation’s log level to logger.Info

db.Debug().Where("name = ?", "jinzhu").First(&User{})

Customize Logger

Refer to GORM’s default logger for how to define your own one

The logger needs to implement the following interface, it accepts context, so you can use it for log tracing

type Interface interface {
LogMode(LogLevel) Interface
Info(context.Context, string, ...interface{})
Warn(context.Context, string, ...interface{})
Error(context.Context, string, ...interface{})
Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)
}

Platinum Sponsors

Gold Sponsors

Platinum Sponsors

Gold Sponsors