Skip to content

Instantly share code, notes, and snippets.

@xflr6
Last active October 12, 2025 10:12
Show Gist options
  • Select an option

  • Save xflr6/84f9bc44b82ae1f0347b to your computer and use it in GitHub Desktop.

Select an option

Save xflr6/84f9bc44b82ae1f0347b to your computer and use it in GitHub Desktop.
Use psycopg2 LoggingConnection with sqlalchemy
"""Use psycopg2 LoggingConnection with SQLAlalchemy."""
import logging
import psycopg2.extras
import sqlalchemy as sa
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger()
class LoggingConnection(psycopg2.extras.LoggingConnection):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.initialize(log)
engine = sa.create_engine('postgresql://postgres@/',
connect_args={'connection_factory': LoggingConnection})
with engine.connect() as conn:
print(conn.scalar(sa.func.version()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment