Home > Backend Development > Golang > How Can I Log MySQL Queries Executed by GORM in Go?

How Can I Log MySQL Queries Executed by GORM in Go?

Patricia Arquette
Release: 2024-12-20 03:20:09
Original
804 people have browsed it

How Can I Log MySQL Queries Executed by GORM in Go?

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:

  1. Initialize the database connection using Open():
db, err := Open(dbType, connectionDSN)
Copy after login
  1. Set the log mode to true:
db.LogMode(true)
Copy after login

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

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!

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