Gorm - 链式执行输出执行的SQL【gorm io版本】

发布时间 2023-06-04 10:36:12作者: 李若盛开

在GROM使用链式操作过程中,我们想要知道最终执行的SQL是什么,本文讲解三种常见的SQL日志打印方法。

一、全局打印所有的SQL

在gorm.io版本中,我们可以在建立连接时指定打印info级别的sql。

import (
    "time"
    
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
)

dsn := "root:5120154230@(localhost)/tonghua?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ //建立连接时指定打印info级别的sql
    Logger: logger.Default.LogMode(logger.Info), //配置日志级别,打印出所有的sql
})
if err != nil {
    panic(err)
}
defer func() {
    sqlDB, err1 := db.DB() //连接池
    if err1 != nil {
        panic(err1)
    }
    // SetMaxIdleConns 用于设置连接池中空闲连接的最大数量。
    sqlDB.SetMaxIdleConns(10)

    // SetMaxOpenConns 设置打开数据库连接的最大数量。
    sqlDB.SetMaxOpenConns(100)
    
    // SetConnMaxLifetime 设置了连接可复用的最大时间。
    sqlDB.SetConnMaxLifetime(time.Hour)
    sqlDB.Close()
}()

 

二、打印单条SQL

单条SQL的打印比较简单,只需要在操作前加Debug()方法, 则相当于将临时将日志级别改为Info。

db.Table("animal").Debug().Select([]string{"name", "age"}).Find(&animals)
// select name,age from animal
db.Table("animal").Debug().Select("count(distinct(name))").Count(&cnt)
// select count(distinct(name)) from animal

  

三、慢查询日志

import (
    "log"
    "os"
    "time"
    
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
)

slowLogger := logger.New(
    //将标准输出作为Writer
    log.New(os.Stdout, "\r\n", log.LstdFlags),
    logger.Config{
        //设定慢查询时间阈值为1ms
        SlowThreshold: 1 * time.Microsecond,
        //设置日志级别,只有Warn和Info级别会输出慢查询日志
        LogLevel: logger.Warn,
    },
)
dsn := "root:5120154230@(localhost)/tonghua?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    Logger: slowLogger,
})