golang gorm Access the underlying mysql query

Gravy picture Gravy · Mar 29, 2016 · Viewed 17.2k times · Source

Is there a way to get the sql query log from https://github.com/jinzhu/gorm?

e.g. in dev environment, it would be useful to be able to log to the console the mysql queries that have been called.

e.g. how to get the underlying sql query log for the following queries:

gorm.Find(&todos)
gorm.Preload("User").Find(&todos)

I am aware that I can call:

gorm.Debug().Find(&todos)
gorm.Debug().Preload("User").Find(&todos)

but I would like to only call Debug() if in dev envrionment and not in production

Answer

Ronna picture Ronna · Mar 29, 2016

This will do the trick:

db, err:= Open(dbType, connectionDSN);
db.LogMode(true)