Accessing the Underlying MySQL Query in Golang Using GORM
Question:
How can I obtain the SQL query log generated by the GORM library? In development environments, it can be valuable to view the MySQL queries that have been executed.
Solution:
Option 1: Using gorm.Debug()
The quick solution is to use the gorm.Debug() method, which enables query logging in both development and production environments:
gorm.Debug().Find(&todos) gorm.Debug().Preload("User").Find(&todos)
Option 2: Using db.LogMode()
A more controlled approach is to use the db.LogMode() method on the underlying database connection. This provides the ability to selectively enable query logging only in development environments:
db, err := Open(dbType, connectionDSN) db.LogMode(true)
By using db.LogMode(true), all subsequent queries executed using this database connection will be logged. This approach allows developers to explicitly enable query logging when desired, without affecting production environments.
The above is the detailed content of How to Access the Underlying MySQL Query Log from GORM in Go?. For more information, please follow other related articles on the PHP Chinese website!