How do I profile slow queries using GORM?

To profile slow queries in GORM (Go Object Relational Mapping), you can utilize the built-in logger to log all the SQL statements executed by GORM. This can help you analyze slow queries in your application.

Enabling GORM Logger for Profiling

To enable logging in GORM, you can set the logger with a custom log level. For profiling slow queries, you typically want to print all queries along with their execution times. Here’s how you can do that:


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

func InitDB() *gorm.DB {
    newLogger := logger.New(
        logrus.StandardLogger(),
        logger.Config{
            LogLevel: logger.Info, // Set log level to Info
            // Other logger configurations...
        },
    )

    db, err := gorm.Open(mysql.Open(""), &gorm.Config{
        Logger: newLogger,
    })

    return db
}
    

Logging Slow Queries Specifically

To focus on slow queries, you can configure the logger to log queries that take longer than a certain threshold. For example, to log queries taking more than 200 milliseconds:


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

func InitDB() *gorm.DB {
    newLogger := logger.New(
        logrus.StandardLogger(),
        logger.Config{
            LogLevel: logger.Info,
            SlowThreshold: 200 * time.Millisecond, // Log queries longer than 200ms
            // Other logger configurations...
        },
    )
    
    db, err := gorm.Open(mysql.Open(""), &gorm.Config{
        Logger: newLogger,
    })

    return db
}
    

With this setup, all your slow queries will be logged, allowing you to identify and optimize them.


GORM Go profiling slow queries SQL logging database optimization