Python psycopg2 - 记录事件

标签 python postgresql psycopg2 pgadmin

我正在使用 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 类未满足的三个要求

  1. 查询执行时间
  2. 受影响的行数
  3. 包含所有事件的完整日志文件。

对于第一个要求,请查看 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/

相关文章:

python - Scikit 学习错误地输入值

linux - 在 Fedora 21 上安装 psycopg2 时出错

python - 这里__init__方法的作用是什么

python - 数数没有。标记化、停用词删除和词干提取后的标记数量

postgresql - TypeORM 中的 Postgres 枚举

postgresql - Finatra 和 Slick 3.1 在响应 header 中返回成功、失败和值

python - 使用python psycopg2保存二进制数据时如何修复 "can' t adapt error

Python unicode 字符串被 psycopg 拒绝

python - 电子商务应用程序中的 Django 用户模型扩展

sql - 复制 CSV 文件,然后分析?一步步?