获取在非DryRun模式下由GORM执行的SQL语句。

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

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.

huangapple
  • 本文由 发表于 2021年6月24日 19:05:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/68114564.html
匿名

发表评论

匿名网友

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

确定