英文:
Get executed SQL by GORM without DryRun Mode
问题
不使用DryRun,是否可以获取Gorm运行的SQL语句?我想要运行SQL语句,如果出现错误,我想要将其记录在日志中,并附带其他一些信息。有没有办法可以检索到已执行的SQL语句?
英文:
Is it possible to get SQL run by Gorm without using DryRun?
I would like to run the SQL, and if this SQL error I would like to record it in a LOG along with several other information. Is there any way I can retrieve this executed SQL?
答案1
得分: 2
有两种方法可以在日志中获取 SQL。
如果你只想输出特定查询的 SQL,可以使用 db.Debug()
将该查询的日志级别更改为 INFO
。
db.Debug().Where("name = ?", "jinzhu").First(&User{})
如果你想在整个应用程序中全局输出 SQL,请在初始化 gorm.DB
实例时配置日志记录器。
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
LogLevel: logger.Info, // Log level Info will output everything
},
)
// 全局模式
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
Logger: newLogger,
})
详细信息请参考 gorm logger。
英文:
There are two ways to achieve getting SQL in the log
If you only want to output SQL for specific query, then using db.Debug()
will change the log level for that query to INFO
.
db.Debug().Where("name = ?", "jinzhu").First(&User{})
If you want to output SQL globally for your application, configure the logger when initialize the gorm.DB
instance
newLogger := logger.New(
log.New(os.Stdout, "\r\n", log.LstdFlags),
logger.Config{
LogLevel: logger.Info, // Log level Info will output everything
},
)
// Globally mode
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{
Logger: newLogger,
})
Details at gorm logger.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论