Golang GORM 访问底层的 MySQL 查询。

huangapple go评论96阅读模式
英文:

golang gorm Access the underlying mysql query

问题

有没有办法从https://github.com/jinzhu/gorm获取SQL查询日志?

例如,在开发环境中,能够将已调用的MySQL查询记录到控制台会很有用。

例如,如何获取以下查询的底层SQL查询日志:

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

我知道可以调用:

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

但我只想在开发环境中调用Debug(),而不在生产环境中调用。

英文:

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

答案1

得分: 63

这样就可以了:

db, err := 打开(dbType, connectionDSN);
db.LogMode(true)
英文:

This will do the trick:

db, err:= Open(dbType, connectionDSN);
db.LogMode(true)

答案2

得分: 41

在新版本(GORM v2)中,使用Logger接口:

import "gorm.io/gorm/logger"


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

对于旧版本(GORM v1):

db, err := Open(dbType, connectionDSN)
db.LogMode(true)

注意:这不仅适用于MySQL,也适用于任何其他数据库驱动程序(例如Postgres,SQLite等)。

英文:

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.).

答案3

得分: 1

你可以使用gorm.SetLogger方法将自己的日志记录器传递给gorm。它使用日志记录器的Print方法来打印日志和SQL查询。对于任何日志记录器(如logrus/go的内置日志记录器),Print方法的日志级别通常设置为INFO。当将日志记录器传递给gorm时,如果将日志级别设置为DEBUG/INFO或更低,您可以通过gorm查看SQL查询和其他日志。

此外,您还可以从配置文件中解析日志级别,并根据环境设置它。

英文:

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

huangapple
  • 本文由 发表于 2016年3月29日 18:14:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/36281394.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定