我如何使用Psycopg2的LoggingConnection?

时间:2015-03-09 19:26:28

标签: python postgresql psycopg2

我想记录psycopg2正在进行的查询,但psycopg2 documentation并没有真正指定如何使用LoggingConnection。

import logging
from psycopg2.extras import LoggingConnection

db_settings = {
    "user": "abcd",
    "password": "efgh",
    "host": "postgres.db",
    "database": "dev",
}

conn = LoggingConnection(**db_settings)

给出错误

  

LoggingConnection(** db_settings)   TypeError:函数最多需要2个参数(给定5个)

2 个答案:

答案 0 :(得分:14)

似乎设置了connection_factory=LoggingConnection作品

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")

答案 1 :(得分:0)

如果您想直接使用LoggingConnection,则需要将DSN作为libpq connection string提供给LoggingConnection() - 键/值连接字符串或连接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')

但是,我可能会使用@kristi演示的连接工厂。