简体   繁体   English

golang gorm 访问底层mysql查询

[英]golang gorm Access the underlying mysql query

Is there a way to get the sql query log from https://github.com/jinzhu/gorm ?有没有办法从https://github.com/jinzhu/gorm获取 sql 查询日志?

eg in dev environment, it would be useful to be able to log to the console the mysql queries that have been called.例如,在开发环境中,能够将已调用的 mysql 查询记录到控制台会很有用。

eg how to get the underlying sql query log for the following queries:例如,如何获取以下查询的底层 sql 查询日志:

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但我只想在开发环境而不是生产环境中调用Debug()

This will do the trick:这将解决问题:

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

In the new version (GORM v2), use the Logger interface:在新版本(GORM v2)中,使用Logger接口:

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

For old version (GORM v1):对于旧版本(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 (eg Postgres, SQLite, etc.).注意:这不是 MySQL 特有的,可以与任何其他数据库驱动程序(例如 Postgres、SQLite 等)一起使用。

You can pass your own logger to gorm using gorm.SetLogger method.您可以使用 gorm.SetLogger 方法将您自己的记录器传递给 gorm。 It uses the Print method of the logger to print logs as well as SQL queries.它使用记录器的 Print 方法来打印日志以及 SQL 查询。 The log level of Print method for any logger(logrus/go's inbuild logger) is generally set to INFO.任何记录器(logrus/go 的内置记录器)的 Print 方法的日志级别通常设置为 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在将记录器传递给 gorm 时,如果您将日志级别设置为低于或等于 INFO(DEBUG/INFO) 的任何内容,您可以通过 gorm 查看 sql 查询和其他日志

Also you can parse the log level from a config file where you can set it based on environment您也可以从配置文件中解析日志级别,您可以在其中根据环境进行设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM