How do I use Psycopg2's LoggingConnection?

前端 未结 2 1877
忘了有多久
忘了有多久 2020-12-20 11:41

I\'d like to log the queries that psycopg2 is making, but the psycopg2 documentation doesn\'t really specify how LoggingConnection should be used.

import log         


        
2条回答
  •  星月不相逢
    2020-12-20 12:19

    Seems like setting the connection_factory=LoggingConnection works

    import logging
    import psycopg2
    from psycopg2.extras import LoggingConnection
    
    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)
    
    db_settings = {
        "user": "abcd",
        "password": "efgh",
        "host": "postgres.db",
        "database": "dev",
    }
    
    conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
    conn.initialize(logger)
    
    cur = conn.cursor()
    cur.execute("SELECT * FROM table LIMIT 5")
    

提交回复
热议问题