Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

gorm.Find(&todos)
gorm.Preload("User").Find(&todos)

I am aware that I can call:

gorm.Debug().Find(&todos)
gorm.Debug().Preload("User").Find(&todos)

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

like image 978
Gravy Avatar asked Mar 29 '16 10:03

Gravy


People also ask

How do I log a query in Gorm?

Current state of logging in GORM In order to enable logging for all queries, we need to invoke the LogMode method with true as the argument. The logs below are for a simple /GET API call which retrieves records from the orders and items table.

Is Gorm slow?

Gorm seem to be extremely slow. The last time takes almost 60s to query. Whereas if I used "database/sql" mysql. QueryRow() its less than 500ms.

What is ORM in Golang?

Golang ORMs Luckily, the Go community has built a number of Object Relational Mapping libraries (ORMs) to allow Go developers to use JSON key:value pair syntax and encoding to map directly to a SQL database like PostgreSQL. ORMs enable developers to use their native programming paradigm to map data to SQL.


3 Answers

This will do the trick:

db, err:= Open(dbType, connectionDSN);
db.LogMode(true)
like image 173
Ronna Avatar answered Sep 23 '22 19:09

Ronna


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);
db.LogMode(true)

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

like image 21
rustyx Avatar answered Sep 22 '22 19:09

rustyx


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

like image 1
Drunk_Debugger Avatar answered Sep 24 '22 19:09

Drunk_Debugger