Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Psycopg2's LoggingConnection?

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 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 takes at most 2 arguments (5 given)

like image 591
k107 Avatar asked Mar 09 '15 19:03

k107


People also ask

What is a RealDictRow?

RealDictRow(cursor) A dict subclass representing a data record. Follow this answer to receive notifications.

Is psycopg async?

Psycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY .


2 Answers

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")
like image 177
k107 Avatar answered Oct 03 '22 22:10

k107


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

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 connection factory like @kristi demonstrated.

like image 32
Lukas Graf Avatar answered Oct 03 '22 21:10

Lukas Graf