Accessing the Underlying MySQL Query in Go with GORM
In development environments, it can be beneficial to log the MySQL queries executed by GORM for debugging purposes. This allows developers to inspect the raw SQL being generated and identify any potential inefficiencies or errors.
To enable query logging in GORM, the following steps can be taken:
db, err := Open(dbType, connectionDSN)
db.LogMode(true)
Once these steps are completed, GORM will automatically log all executed queries to the console. This includes queries generated by both gorm.Find() and gorm.Preload().
Conditional Query Logging
For environments where query logging is only desired in development, a conditional approach can be employed:
if os.Getenv("ENV") == "dev" { db.LogMode(true) }
In this example, query logging will only be enabled if the environment variable ENV is set to "dev". This allows developers to easily toggle query logging based on the execution environment.
The above is the detailed content of How Can I Log MySQL Queries Executed by GORM in Go?. For more information, please follow other related articles on the PHP Chinese website!