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 writerlogger.Config{SlowThreshold: time.Second, // Slow SQL thresholdLogLevel: logger.Silent, // Log levelIgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for loggerColorful: false, // Disable color},)// Globally modedb, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{Logger: newLogger,})// Continuous session modetx := 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) InterfaceInfo(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)}