Python psycopg2 – 记录事件
作者:互联网
我正在使用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类没有满足
>查询执行时间
>受影响的行数
>包含所有事件的完整日志文件.
对于第一个要求,请查看psycopg2.extras中MinTimeLoggingConnection类的源代码.它对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类型,其中包含此附加功能.
我的尝试如下.只需在代码中用LoggingConnection2替换LoggingConnection,这应该都可以.作为旁注,您不需要为第二个查询创建新光标.您可以在定义第二个查询后再次调用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,postgresql,psycopg2,pgadmin 来源: https://codeday.me/bug/20190629/1329740.html