Skip to content

Instantly share code, notes, and snippets.

@xflr6
Last active June 4, 2022 08:43
Show Gist options
  • Save xflr6/84f9bc44b82ae1f0347b to your computer and use it in GitHub Desktop.
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})
print(engine.scalar(sa.func.version()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment