forked from mtusi2026/mtusi2026lab6
42 lines
1.2 KiB
Go
42 lines
1.2 KiB
Go
package observability
|
|
|
|
import (
|
|
"context"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/trace"
|
|
"strings"
|
|
"sync/atomic"
|
|
)
|
|
|
|
type DBTracer struct{}
|
|
|
|
func (DBTracer) TraceQueryStart(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryStartData) context.Context {
|
|
op := "query"
|
|
if words := strings.Fields(d.SQL); len(words) > 0 {
|
|
switch strings.ToUpper(words[0]) {
|
|
case "SELECT", "UPDATE", "INSERT", "DELETE", "BEGIN", "COMMIT", "ROLLBACK":
|
|
op = strings.ToUpper(words[0])
|
|
}
|
|
}
|
|
ctx, span := Start(ctx, "postgresql "+op, trace.SpanKindClient)
|
|
span.SetAttributes(attribute.String("db.system.name", "postgresql"), attribute.String("db.operation.name", op))
|
|
return ctx
|
|
}
|
|
func (DBTracer) TraceQueryEnd(ctx context.Context, _ *pgx.Conn, d pgx.TraceQueryEndData) {
|
|
span := trace.SpanFromContext(ctx)
|
|
Result(span, d.Err)
|
|
span.End()
|
|
}
|
|
|
|
var waiting atomic.Int64
|
|
|
|
func (DBTracer) TraceAcquireStart(ctx context.Context, _ *pgxpool.Pool, _ pgxpool.TraceAcquireStartData) context.Context {
|
|
waiting.Add(1)
|
|
return ctx
|
|
}
|
|
func (DBTracer) TraceAcquireEnd(context.Context, *pgxpool.Pool, pgxpool.TraceAcquireEndData) {
|
|
waiting.Add(-1)
|
|
}
|