Skip to content

Commit

Permalink
adds tracer for slow query log
Browse files Browse the repository at this point in the history
  • Loading branch information
timbastin committed Aug 30, 2024
1 parent ff1d750 commit a9e731d
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions packages/store/dbstore.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"sync"
"time"

"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/l3montree-dev/oh-my-honeypot/packages/honeypot"
"github.com/l3montree-dev/oh-my-honeypot/packages/types"
Expand Down Expand Up @@ -234,6 +235,22 @@ func (p *PostgreSQL) spamInsert(attackID string, name string, email string) {
}
}

type tracer struct {
}

func (t tracer) TraceQueryStart(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryStartData) context.Context {
newCtx := context.WithValue(ctx, "start", time.Now())
return context.WithValue(newCtx, "query", data.SQL)
}

func (t tracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) {
// if the query takes more than 200ms, log it
if time.Since(ctx.Value("start").(time.Time)) > 200*time.Millisecond {
slog.Warn("Slow query", "query", time.Since(ctx.Value("start").(time.Time)), "err", data.Err)
fmt.Println(ctx.Value("query"))
}
}

// Start initializes the PostgreSQL database connection.
func (p *PostgreSQL) Start(host, port, user, password, dbname string) error {
connStr := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
Expand All @@ -252,6 +269,8 @@ func (p *PostgreSQL) Start(host, port, user, password, dbname string) error {
dbConfig.HealthCheckPeriod = time.Minute
dbConfig.ConnConfig.ConnectTimeout = time.Second * 5

dbConfig.ConnConfig.Tracer = &tracer{}

connPool, err := pgxpool.NewWithConfig(context.Background(), dbConfig)

if err != nil {
Expand Down Expand Up @@ -327,6 +346,9 @@ func (p *PostgreSQL) Start(host, port, user, password, dbname string) error {
}

slog.Info("PostgreSQL store started")

honeypotIds := p.honeypotIds()
slog.Info("Honeypot IDs", "ids", honeypotIds)
return nil
}

Expand Down

0 comments on commit a9e731d

Please sign in to comment.