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
MinConn: 2, // Keep these low for dev, high for production
MaxConn: 10,
SlowQueryThresholdMs: 200,
},
Auth: AuthConfig{
CookieDomain: ".handmade.local",

View File

@ -37,14 +37,15 @@ type HMNConfig struct {
}
type PostgresConfig struct {
User string
Password string
Hostname string
Port int
DbName string
LogLevel tracelog.LogLevel
MinConn int32
MaxConn int32
User string
Password string
Hostname string
Port int
DbName string
LogLevel tracelog.LogLevel
MinConn int32
MaxConn int32
SlowQueryThresholdMs int
}
type AuthConfig struct {

View File

@ -7,6 +7,7 @@ import (
"reflect"
"regexp"
"strings"
"time"
"git.handmade.network/hmn/hmn/src/config"
"git.handmade.network/hmn/hmn/src/logging"
@ -298,6 +299,7 @@ func QueryIterator[T any](
compiled := compileQuery(query, destType)
queryStart := time.Now()
rows, err := conn.Query(ctx, compiled.query, args...)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
@ -305,6 +307,14 @@ func QueryIterator[T any](
}
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]{
fieldPaths: compiled.fieldPaths,