内置慢查询分析器:不依赖外部工具的实时SQL监控面板
在Django admin中集成一个实时SQL分析器,记录执行时间超过阈值的查询,并展示调用堆栈和ORM代码行号。 · 难度:入门 · +10XP
SQL查询探针
利用django.db.connection.execute_wrapper钩子,在每次SQL执行前后记录时间戳、堆栈帧和参数。将超过阈值的查询持久化到SlowQueryLog模型。教程会构建一个可排序、可搜索的admin视图,显示查询原文、时长、触发路径和ORM链。还提供一键发送到Sentry或发送邮件告警的功能。你还可以学习如何在线程安全的条件下聚合多次相同查询。
import time
import traceback
from django.db import connection
class SlowQueryProfiler:
def __init__(self, threshold=1.0):
self.threshold = threshold
def __enter__(self):
self.old_execute = connection.execute_wrapper
connection.execute_wrapper = self.wrapper
def wrapper(self, execute, sql, params, many, context):
start = time.monotonic()
result = execute(sql, params, many, context)
duration = time.monotonic() - start
if duration > self.threshold:
SlowQueryLog.objects.create(
sql=sql,
duration=duration,
stack=traceback.format_stack()
)
return result