You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在DEBUG=False时启用Django的django.db.backends日志记录?

如何在Django生产环境(DEBUG=False)下记录SQL查询日志

Django官方文档中关于django.db.backends的日志配置明确说明:出于性能考虑,无论日志级别或处理器如何配置,仅当settings.DEBUG设为True时才会启用SQL日志记录。

当DEBUG = False时,即便配置了正确的LOGGING规则(如下所示),也无法输出数据库查询的DEBUG级日志:

DEBUG = False
LOGGING = {
    "version": 1,
    "disable_existing_loggers": True,
    "root": {"handlers": [ "gcp_structured_logging"]},
    "handlers": {
        "gcp_structured_logging": {
            "level": "DEBUG",
            "class": "django_gcp.logging.GoogleStructuredLogsHandler",
        }
    },
    "loggers": {
        'django.db.backends': {
            'handlers': ["gcp_structured_logging"],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

这就导致生产环境无法启用SQL日志记录——生产环境显然不能设置DEBUG=True,但排查性能问题时又确实需要这些日志(计划短暂启用收集日志,之后搭建真实负载测试和数据库基准测试场景)。

绕过限制的解决方案

通过猴子补丁(Monkey Patch)修改Django的数据库游标执行逻辑,移除对DEBUG状态的检查,即可强制开启SQL日志记录:

import logging
from django.db.backends.utils import CursorWrapper

def patched_execute(self, sql, params=None):
    # 保留原始执行逻辑
    result = self._original_execute(sql, params)
    # 手动触发DEBUG日志,无需检查DEBUG设置
    if self.db.logger.isEnabledFor(logging.DEBUG):
        duration = self.db.queries[-1]['time']
        self.db.logger.debug(
            f"({duration:.3f}) {sql % (params if params else ())}",
            extra={'duration': duration}
        )
    return result

def patched_executemany(self, sql, param_list):
    result = self._original_executemany(sql, param_list)
    if self.db.logger.isEnabledFor(logging.DEBUG):
        duration = self.db.queries[-1]['time']
        display_params = param_list[0] if param_list else ()
        self.db.logger.debug(
            f"({duration:.3f}) {sql % display_params}",
            extra={'duration': duration}
        )
    return result

# 替换原始方法
CursorWrapper._original_execute = CursorWrapper.execute
CursorWrapper.execute = patched_execute
CursorWrapper._original_executemany = CursorWrapper.executemany
CursorWrapper.executemany = patched_executemany

将上述代码添加到项目的settings.py末尾,或者项目初始化时加载的文件(如wsgi.py/asgi.py)中,同时确保LOGGING配置中django.db.backends的日志级别设为DEBUG,即可在DEBUG=False时正常记录SQL查询日志。

替代方案推荐

最终发现django-silk库也能满足性能排查需求:它虽然不是直接绕过Django的SQL日志限制,但提供了更全面的性能分析功能,包括SQL查询记录、请求耗时统计、慢查询标记等,适合需要深度排查性能问题的场景,有相同需求的开发者可以尝试。

内容的提问来源于stack exchange,提问作者thclark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 10:57:24