Files
3ybactuk-marketplace-go-ser…/loms/internal/infra/db/postgres/tracer.go
Никита Шубин 4396bebe80 [hw-7] add metrics, tracing
2025-07-26 14:15:40 +00:00

39 lines
859 B
Go

package postgres
import (
"context"
"strings"
"time"
"route256/loms/internal/infra/grpc/metrics"
"github.com/jackc/pgx/v5"
)
type startKey struct{}
type promTracer struct{}
func (promTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, _ pgx.TraceQueryStartData) context.Context {
return context.WithValue(ctx, startKey{}, time.Now())
}
func (promTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, data pgx.TraceQueryEndData) {
start, _ := ctx.Value(startKey{}).(time.Time)
sql := strings.TrimSpace(strings.ToLower(data.CommandTag.String()))
parts := strings.SplitN(sql, " ", 2)
category := "unknown"
if len(parts) > 0 {
category = parts[0]
}
errLabel := "none"
if data.Err != nil {
errLabel = "error"
}
metrics.IncDBQueryCount(category, errLabel)
metrics.StoreDBQueryDuration(category, errLabel, time.Since(start))
}