Get executed SQL by GORM without DryRun Mode

Viewed 1553

Is it possible to get SQL run by Gorm without using DryRun? I would like to run the SQL, and if this SQL error I would like to record it in a LOG along with several other information. Is there any way I can retrieve this executed SQL?

1 Answers

There are two ways to achieve getting SQL in the log

If you only want to output SQL for specific query, then using db.Debug() will change the log level for that query to INFO.

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

If you want to output SQL globally for your application, configure the logger when initialize the gorm.DB instance

newLogger := logger.New(
    log.New(os.Stdout, "\r\n", log.LstdFlags),
    logger.Config{
        LogLevel:                   logger.Info, // Log level Info will output everything
    },
)

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

Details at gorm logger.

Related