2014-09-10 48 views

回答

1

這裏的記錄與執行時間的查詢長於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()