How to use Psycopg2 LoggingConnection?

I would like to register the requests that psycopg2 creates, but the psycopg2 documentation does not actually indicate how to use LoggingConnection.

import logging from psycopg2.extras import LoggingConnection db_settings = { "user": "abcd", "password": "efgh", "host": "postgres.db", "database": "dev", } conn = LoggingConnection(**db_settings) 

Gives an error

LoggingConnection (** db_settings) TypeError: function accepts no more than 2 arguments (5 data)

+5
source share
2 answers

Setting connection_factory=LoggingConnection work

 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") 
+10
source

If you want to use LoggingConnection directly, you need to provide the DSN as the libpq connection string before LoggingConnection() - either the key / value string or the connection URI:

 from psycopg2.extras import LoggingConnection DSN = "postgresql://john: secret@localhost /mydb" #DSN = "host=localhost dbname=mydb user=john password=secret" logfile = open('db.log', 'a') conn = LoggingConnection(DSN) conn.initialize(logfile) cur = conn.cursor() cur.execute('SELECT 1') 

However, I would probably use a factory connection, as shown by @kristi.

0
source

Source: https://habr.com/ru/post/1215005/


All Articles