Python 如何获取查询执行时间的psycopg2日志?
我试图获得psycopg2执行的查询的性能统计数据,但文档/示例仍然显得模糊,不够清晰 我至少已经通过记录器进行了调试。 我需要做什么来访问查询的性能数据?我想得到查询执行时间的数字 是否有我可以访问的方法,或者需要初始化其他东西来输出查询执行时间 以下是我迄今为止所掌握的内容的拼凑摘录:Python 如何获取查询执行时间的psycopg2日志?,python,postgresql,Python,Postgresql,我试图获得psycopg2执行的查询的性能统计数据,但文档/示例仍然显得模糊,不够清晰 我至少已经通过记录器进行了调试。 我需要做什么来访问查询的性能数据?我想得到查询执行时间的数字 是否有我可以访问的方法,或者需要初始化其他东西来输出查询执行时间 以下是我迄今为止所掌握的内容的拼凑摘录: import psycopg2 import psycopg2.extensions from psycopg2.extras import LoggingConnection import logging
import psycopg2
import psycopg2.extensions
from psycopg2.extras import LoggingConnection
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# set higher up in script
db_settings = {
"user": user,
"password": password,
"host": host,
"database": dbname,
}
query_txt = "[query_txt_from file]"
conn = psycopg2.connect(connection_factory=LoggingConnection, **db_settings)
conn.initialize(logger)
cur = conn.cursor()
cur.execute(query_txt)
我得到
DEBUG:__main__: [the query executed]
很容易在执行开始时设置时间戳,并在执行结束时计算持续时间。您需要自己的LoggingConnection和LoggingCursor的简单子类。请参阅我的示例代码 这是基于MinTimeLoggingConnection的源代码,您可以在
psycopg2/extras.py
source中找到它
import time
import psycopg2
import psycopg2.extensions
from psycopg2.extras import LoggingConnection, LoggingCursor
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# MyLoggingCursor simply sets self.timestamp at start of each query
class MyLoggingCursor(LoggingCursor):
def execute(self, query, vars=None):
self.timestamp = time.time()
return super(MyLoggingCursor, self).execute(query, vars)
def callproc(self, procname, vars=None):
self.timestamp = time.time()
return super(MyLoggingCursor, self).callproc(procname, vars)
# MyLogging Connection:
# a) calls MyLoggingCursor rather than the default
# b) adds resulting execution (+ transport) time via filter()
class MyLoggingConnection(LoggingConnection):
def filter(self, msg, curs):
return msg + " %d ms" % int((time.time() - curs.timestamp) * 1000)
def cursor(self, *args, **kwargs):
kwargs.setdefault('cursor_factory', MyLoggingCursor)
return LoggingConnection.cursor(self, *args, **kwargs)
db_settings = {
....
}
query_txt = "[query_text_from file]"
conn = psycopg2.connect(connection_factory=MyLoggingConnection, **db_settings)
conn.initialize(logger)
cur = conn.cursor()
cur.execute(query_text)
您将得到:
DEBUG: __main__:[query] 3 ms
在
filter()
中,如果小于某个值,您可以更改格式,或者选择不显示。PostgreSQL不会收集和报告服务器端查询执行时间、SAN客户端延迟和数据传输时间。所以psycopg2不能报告。psycopg2可以收集从请求执行查询到获得第一个结果所花费的时间。我不知道是不是。您想要的查询执行时间到底是多少?从发送查询到获取第一个结果的总时间?最后结果如何?只是服务器端执行?服务器端执行;尽可能接近\时间;也许我必须通过系统控制台输出“配置中的log\u min\u duration\u statement=0,然后设置client\u min\u messages=log”来访问日志功能;或者看看我是否可以访问类似EXPLAIN的功能,它也有执行时间。\time
在psql中是全天的,包括网络延迟和结果传输时间