我正在使用 psycopg2,但在将事件(已执行的查询、通知、错误)记录到文件时遇到了问题。我想在 PgAdmin 历史窗口中获得效果。
例如我正在执行这个查询:
insert into city(id, name, countrycode, district, population) values (4080,'Savilla', 'ESP', 'andalucia', 1000000)
在 PgAdmin 中我看到这样的效果:
Executing query:
insert into city(id, name, countrycode, district, population) values (4080,'Sevilla', 'ESP', 'andalucia', 1000000)
Query executed in 26 ms.
One row affected.
我可以使用 psycopg2 获得类似的效果吗?
我尝试使用 LoggingCursor ,但它对我来说并不令人满意,因为它只记录查询。
感谢您的帮助。
编辑:
我的代码:
conn = psycopg2.extras.LoggingConnection(DSN)
File=open('log.log','a')
File.write('================================')
psycopg2.extras.LoggingConnection.initialize(conn,File)
File.write('\n'+time.strftime("%Y-%m-%d %H:%M:%S") + '---Executing query:\n\t')
q="""insert into city(id, name, countrycode, district, population) values (4080,'Sevilla', 'ESP', 'andalucia', 10000)"""
c=conn.cursor()
c.execute(q)
File.write('\n'+time.strftime("%Y-%m-%d %H:%M:%S") + '---Executing query:\n\t')
q="""delete from city where id = 4080"""
c=conn.cursor()
c.execute(q)
conn.commit()
File.close()
这是我的输出日志:
================================
2012-12-30 22:42:31---Executing query:
insert into city(id, name, countrycode, district, population) values (4080,'Sevilla', 'ESP', 'andalucia', 10000)
2012-12-30 22:42:31---Executing query:
delete from city where id = 4080
我想在日志文件中查看有关受影响行数和错误信息的信息。最后,我想要一个包含所有事件的完整日志文件。
最佳答案
据我所知,您有 LoggingCursor 类未满足的三个要求
- 查询执行时间
- 受影响的行数
- 包含所有事件的完整日志文件。
对于第一个要求,请查看 MinTimeLoggingConnection 的源代码psycopg2.extras 中的类。它对LoggingConnection进行子类化,输出超过最小时间的查询的执行时间(注意这个需要和MinTimeLoggingCursor一起使用)。
对于第二个要求,rowcount attribute游标类的指定
the number of rows that the last execute*() produced (for DQL statements like SELECT) or affected (for DML statements like UPDATE or INSERT)
因此,应该可以创建您自己的类型的 LoggingConnection 和 LoggingCursor,其中包括此附加功能。
我的尝试如下。只需在您的代码中将 LoggingConnection
替换为 LoggingConnection2
即可,一切正常。作为旁注,您不需要为第二个查询创建新游标。您可以在定义第二个查询后再次调用 c.execute(q)
。
import psycopg2
import os
import time
from psycopg2.extras import LoggingConnection
from psycopg2.extras import LoggingCursor
class LoggingConnection2(psycopg2.extras.LoggingConnection):
def initialize(self, logobj):
LoggingConnection.initialize(self, logobj)
def filter(self, msg, curs):
t = (time.time() - curs.timestamp) * 1000
return msg + os.linesep + 'Query executed in: {0:.2f} ms. {1} row(s) affected.'.format(t, curs.rowcount)
def cursor(self, *args, **kwargs):
kwargs.setdefault('cursor_factory', LoggingCursor2)
return super(LoggingConnection, self).cursor(*args, **kwargs)
class LoggingCursor2(psycopg2.extras.LoggingCursor):
def execute(self, query, vars=None):
self.timestamp = time.time()
return LoggingCursor.execute(self, query, vars)
def callproc(self, procname, vars=None):
self.timestamp = time.time()
return LoggingCursor.execute(self, procname, vars)
我不确定如何创建所有事件的完整日志,但是 notices attribute连接类的可能感兴趣。
关于Python psycopg2 - 记录事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14087853/