Slow query logging

This commit is contained in:
Asaf Gartner 2024-07-06 11:03:57 +03:00
parent 36aec19898
commit 43a3178b08
3 changed files with 20 additions and 8 deletions

View File

@ -23,6 +23,7 @@ var Config = HMNConfig{
LogLevel: tracelog.LogLevelError, // LogLevelWarn is recommended for production LogLevel: tracelog.LogLevelError, // LogLevelWarn is recommended for production
MinConn: 2, // Keep these low for dev, high for production MinConn: 2, // Keep these low for dev, high for production
MaxConn: 10, MaxConn: 10,
SlowQueryThresholdMs: 200,
}, },
Auth: AuthConfig{ Auth: AuthConfig{
CookieDomain: ".handmade.local", CookieDomain: ".handmade.local",

View File

@ -45,6 +45,7 @@ type PostgresConfig struct {
LogLevel tracelog.LogLevel LogLevel tracelog.LogLevel
MinConn int32 MinConn int32
MaxConn int32 MaxConn int32
SlowQueryThresholdMs int
} }
type AuthConfig struct { type AuthConfig struct {

View File

@ -7,6 +7,7 @@ import (
"reflect" "reflect"
"regexp" "regexp"
"strings" "strings"
"time"
"git.handmade.network/hmn/hmn/src/config" "git.handmade.network/hmn/hmn/src/config"
"git.handmade.network/hmn/hmn/src/logging" "git.handmade.network/hmn/hmn/src/logging"
@ -298,6 +299,7 @@ func QueryIterator[T any](
compiled := compileQuery(query, destType) compiled := compileQuery(query, destType)
queryStart := time.Now()
rows, err := conn.Query(ctx, compiled.query, args...) rows, err := conn.Query(ctx, compiled.query, args...)
if err != nil { if err != nil {
if errors.Is(err, context.DeadlineExceeded) { if errors.Is(err, context.DeadlineExceeded) {
@ -305,6 +307,14 @@ func QueryIterator[T any](
} }
return nil, err return nil, err
} }
duration := time.Now().Sub(queryStart)
if config.Config.Postgres.SlowQueryThresholdMs > 0 && duration > time.Duration(config.Config.Postgres.SlowQueryThresholdMs)*time.Millisecond {
logging.Warn().
Interface("Duration", duration.String()).
Interface("Query", strings.ReplaceAll(strings.ReplaceAll(compiled.query, "\n", " "), "\t", " ")).
Interface("Args", args).
Msg("Slow query")
}
it := &Iterator[T]{ it := &Iterator[T]{
fieldPaths: compiled.fieldPaths, fieldPaths: compiled.fieldPaths,