golang gorm Access the underlying mysql query

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:


I am aware that I can call:


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


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This will do the trick:

db, err:= Open(dbType, connectionDSN);

Method 2

In the new version (GORM v2), use the Logger interface:

import "gorm.io/gorm/logger"

db, err := gorm.Open(mysql.Open(connectionDSN), &gorm.Config{
    Logger: logger.Default.LogMode(logger.Info),

For old version (GORM v1):

db, err:= Open(dbType, connectionDSN);

Note: this is not specific to MySQL and will work with any other DB driver (e.g. Postgres, SQLite, etc.).

Method 3

You can pass your own logger to gorm using gorm.SetLogger method. It uses the Print method of the logger to print logs as well as SQL queries. The log level of Print method for any logger(logrus/go’s inbuild logger) is generally set to INFO. While passing the logger to gorm, if you set the log level to anything below or equal to INFO(DEBUG/INFO) you can see the sql queries and other logs by gorm

Also you can parse the log level from a config file where you can set it based on environment

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x