Django 记录长时间执行的查询
有没有办法记录我这个Django应用中执行时间很长的数据库查询?
1 个回答
4
这里有一个中间件,它会记录执行时间超过1秒的查询:
from django.db import connection
import logging
LONG_QUERY_TIME_SEC = 1
class LongQueryLogMiddleware:
def process_response ( self, request, response ):
for q in connection.queries:
if float(q['time']) >= LONG_QUERY_TIME_SEC:
logging.warning("Found long query (%s sec): %s", q['time'], q['sql'])
return response
请注意,由于 connection.queries
是在整个进程中共享的,所以查询可能会被记录两次。我们可以在函数结束时运行以下代码来解决这个问题:
from django.db import reset_queries
reset_queries()