很容易在执行开始时设置时间戳并在结束时计算持续时间。您将需要自己的LoggingConnection和LoggingCursor子类。参见我的示例代码。
这基于您可以在
psycopg2/extras.py源代码中找到的MinTimeLoggingConnection的源代码。
import timeimport psycopg2import psycopg2.extensionsfrom psycopg2.extras import LoggingConnection, LoggingCursorimport logginglogging.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(),您可以更改格式,或者如果低于一定值选择不显示。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)