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:

  1. newLogger := logger.New(
  2. log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
  3. logger.Config{
  4. SlowThreshold: time.Second, // Slow SQL threshold
  5. LogLevel: logger.Silent, // Log level
  6. IgnoreRecordNotFoundError: true, // Ignore ErrRecordNotFound error for logger
  7. ParameterizedQueries: true, // Don't include params in the SQL log
  8. Colorful: false, // Disable color
  9. },
  10. )
  11. // Globally mode
  12. db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
  13. Logger: newLogger,
  14. })
  15. // Continuous session mode
  16. tx := db.Session(&Session{Logger: newLogger})
  17. tx.First(&user)
  18. tx.Model(&user).Update("Age", 18)

Log Levels

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

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

Debug

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

  1. 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

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