[Python] Why isn't python 3 psycopg2 LoggingConnection logging to file?

Discussão em 'Python' iniciado por Stack, Julho 21, 2025.

  1. Stack

    Stack Membro Participativo

    I have a pre-existing class to handle all the db operations for python3 based queries/updates/inserts to postgres. Now I want to add psycopg2 transaction logging to capture what is actually sent to the db. I was directed to psycopg2.extras LoggingConnection, but I haven't been able to make it work in this existing class below:

    class dbops:
    def __init__(self):
    db_con_param = [dbconconfig['DB']['user'],
    dbconconfig['DB']['pass'],
    dbconconfig['DB']['db'],
    dbconconfig['DB']['port'],
    dbconconfig['DB']['host']
    ]
    self._conn = psycopg2.connect(
    user=db_con_param[0],
    password=db_con_param[1],
    database=db_con_param[2],
    port=db_con_param[3],
    host=db_con_param[4])
    self._cursor = self._conn.cursor()
    def __enter__(self):
    return self
    def __exit__(self, exc_type, exc_val, exc_tb):
    self.close()
    @property
    def connection(self):
    return self._conn
    @property
    def cursor(self):
    return self._cursor
    def commit(self):
    self.connection.commit()
    def close(self, commit=True):
    if commit:
    self.commit()
    self.connection.close()
    def execute(self, sql, params=None):
    self.cursor.execute(sql, params or ())
    def fetchall(self):
    return self.cursor.fetchall()
    def fetchone(self):
    return self.cursor.fetchone()
    def query(self, sql, params=None):
    self.cursor.execute(sql, params or ())
    return self.fetchall()
    def generic_insert(self, sql, params):
    self.cursor.execute(sql)
    rowcount = self.cursor.rowcount
    return rowcount
    def generic_truncate(self, sql):
    self.cursor.execute(sql)
    rowcount = self.cursor.rowcount
    return rowcount


    In the file containing the class, I have imported LoggingConnections with:

    import psycopg2
    from psycopg2.extras import LoggingConnection


    In that file I've also cfg'd the logger with:

    logging.basicConfig(level=logging.DEBUG)
    logger = logging.getLogger(__name__)


    I've defined a file/handler to the logger with:

    file_handler = logging.FileHandler('postgresdbops.log')
    logger.addHandler(file_handler)


    I have added the connection factory, and initialized the connection within the class:

    self._conn = psycopg2.connect(
    connection_factory=LoggingConnection,
    user=db_con_param[0],
    password=db_con_param[1],
    database=db_con_param[2],
    port=db_con_param[3],
    host=db_con_param[4])
    self._conn.initialize(logger)
    self._cursor = self._conn.cursor()


    These changes produce the log file postgresdbops.log, but it remains empty even after executions that I confirm are successful via psql client. I sure do need some help!

    Continue reading...

Compartilhe esta Página