pgxctx

package
v0.0.0-...-647feed Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package pgxctx provides utilities for using recording slow query metrics and logging for pgxpool.

Example
package main

import (
	"context"
	"os"

	"github.com/LOKE/pkg/pgxctx"
	"github.com/go-kit/log"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/prometheus/client_golang/prometheus"
)

func main() {
	logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))

	cfg, err := pgxpool.ParseConfig("postgres://example.com")
	if err != nil {
		panic(err)
	}

	cfg.ConnConfig.Tracer, err = pgxctx.NewLogger(
		log.WithPrefix(logger, "service", "pg-pool"),
		prometheus.DefaultRegisterer,
	)
	if err != nil {
		panic(err)
	}

	pool, err := pgxpool.NewWithConfig(context.Background(), cfg)
	if err != nil {
		panic(err)
	}

	prometheus.MustRegister(pgxctx.NewPrometheusCollector(pool))
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewLogger

func NewLogger(logger log.Logger, reg prometheus.Registerer) (pgx.QueryTracer, error)

NewLogger returns a new pgx.QueryTracer that logs slow queries and query durations using the given logger and prometheus registerer. The returned tracer should be set on the pgx connection pool.

func NewPrometheusCollector

func NewPrometheusCollector(pool *pgxpool.Pool) prometheus.Collector

NewPrometheusCollector returns a prometheus.Collector that collects metrics from the given pgx pool. It collects connection state metrics such as constructing, acquired, and idle connections. The returned collector should be registered with the prometheus client.

func WithContext

func WithContext(ctx context.Context, name string, opts ...ContextOption) context.Context

WithContext returns a new context with the given name and options. It should be passed directly to Exec, Query, or QueryRow. Queries executed with this context will be logged with the given name on metrics and slow query logs.

Example
package main

import (
	"context"
	"time"

	"github.com/LOKE/pkg/pgxctx"
	"github.com/jackc/pgx/v5/pgxpool"
)

func main() {
	var pool *pgxpool.Pool
	ctx := context.Background()

	pool.QueryRow(pgxctx.WithContext(ctx, "OrderRepo.GetOrder",
		pgxctx.WithSlowQueryThreshold(100*time.Millisecond),
	), `
		SELECT * FROM orders WHERE id = $1
	`, 1)
}

Types

type ContextOption

type ContextOption func(*ctxData)

func WithSlowQueryThreshold

func WithSlowQueryThreshold(threshold time.Duration) ContextOption

WithSlowQueryThreshold sets the slow query threshold for the context. Queries that take longer than this threshold will be logged as slow queries.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL