mirror of
https://github.com/3ybactuk/marketplace-go-service-project.git
synced 2025-10-30 14:03:45 +03:00
[hw-7] add metrics, tracing
This commit is contained in:
38
loms/internal/infra/db/postgres/tracer.go
Normal file
38
loms/internal/infra/db/postgres/tracer.go
Normal file
@@ -0,0 +1,38 @@
|
||||
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))
|
||||
}
|
||||
Reference in New Issue
Block a user