Home > Backend Development > Golang > How to Access the Underlying MySQL Query Log from GORM in Go?

How to Access the Underlying MySQL Query Log from GORM in Go?

Linda Hamilton
Release: 2024-12-13 12:49:10
Original
197 people have browsed it

How to Access the Underlying MySQL Query Log from GORM in Go?

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template