Created
March 28, 2025 14:43
-
-
Save bartolsthoorn/174a57b36aa8b62e46523f1253438195 to your computer and use it in GitHub Desktop.
Example of logging with pgxpool v5
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func main() { | |
// postgres client | |
ctx := context.Background() | |
connStr := os.Getenv("DB_CONNECTION_STRING") | |
cc, err := pgxpool.ParseConfig(connStr) | |
if err != nil { | |
log.Fatalf("Failed to parse config: %v", err) | |
} | |
cc.MinConns = 5 | |
cc.MaxConns = 10 | |
logger, err := zap.NewDevelopment() | |
if err != nil { | |
log.Fatalf("failed to create logger: %v", err) | |
} | |
cc.ConnConfig.Tracer = &myQueryTracer{ | |
log: logger.Sugar(), | |
} | |
// Create a connection pool using the configuration. | |
conn, err := pgxpool.NewWithConfig(ctx, cc) | |
if err != nil { | |
log.Fatalf("failed opening connection to postgres: %v", err) | |
} | |
defer conn.Close() | |
db := queries.New(conn) | |
} | |
type myQueryTracer struct { | |
log *zap.SugaredLogger | |
} | |
func (tracer *myQueryTracer) TraceQueryStart( | |
ctx context.Context, | |
_ *pgx.Conn, | |
data pgx.TraceQueryStartData) context.Context { | |
tracer.log.Debugw("Executing command", "sql", data.SQL, "args", data.Args) | |
return ctx | |
} | |
func (tracer *myQueryTracer) TraceQueryEnd(ctx context.Context, conn *pgx.Conn, data pgx.TraceQueryEndData) { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment