Skip to main content

Diagnostics

Diagnostics warn about patterns no single query shows: a statement repeated in a loop, a request that spends too long in the database, a join that multiplies rows. They count per scope, usually one web request, and add a small cost per statement.

Turn it on​

db, err := ant.Open[AppDB](ctx, postgres.Dialect, dsn,
ant.WithDiagnostics(ant.Diagnostics{
RepeatLimit: 10,
Budget: 500 * time.Millisecond,
Alert: func(ctx context.Context, a ant.Alert) {
slog.Warn("database", "kind", a.Kind, "message", a.Message, "sql", a.SQL)
},
}),
)

RepeatLimit and Budget are limits for each scope. The default Alert logs through slog.

Start a scope for each request​

ant.Watch returns a context that starts a scope. Without one, repeats and budgets are not counted. Wrap each request in middleware:

func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r.WithContext(ant.Watch(r.Context())))
})
}

What it reports​

KindMeans
repeatedOne statement ran more than RepeatLimit times in a scope
budgetStatements together took longer than Budget, which a slow-query log misses when each one is fast
cartesianA query joined two to-many relations. This reports with or without a scope