Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get executed SQL by GORM without DryRun Mode

Tags:

go

go-gorm

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?

like image 811
Eduardo Mior Avatar asked Oct 28 '25 07:10

Eduardo Mior


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.

like image 181
Tranvu Xuannhat Avatar answered Oct 31 '25 08:10

Tranvu Xuannhat