How to Use zerolog for High-Performance Logging in Go

Connect pgx to zerolog using the pgx-zerolog adapter to enable high-performance structured JSON logging for PostgreSQL operations.

Use the pgx-zerolog adapter to connect the pgx driver's tracing system to a zerolog logger for high-performance JSON logging. This adapter implements the pgx.LogLevel interface, allowing pgx to route connection and query logs directly into your zerolog pipeline without reflection overhead.

import (
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/stdlib"
	"github.com/jackc/pgx-zerolog"
	"github.com/rs/zerolog"
	"os"
)

func main() {
	logger := zerolog.New(os.Stdout).With().Timestamp().Logger()
	config, _ := pgx.ParseConfig(os.Getenv("DATABASE_URL"))
	config.Logger = pgxzerolog.NewLogger(logger)
	config.LogLevel = pgx.LogLevelDebug

	conn, err := pgx.ConnectConfig(context.Background(), config)
	if err != nil {
		logger.Fatal().Err(err).Msg("failed to connect")
	}
	defer conn.Close(context.Background())
}