django - 即使 DEBUG=False 也记录 SQL 查询
问题描述
这是我的日志配置settings.py
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
'file': {
'class': 'logging.FileHandler',
'filename': os.path.join(BASE_DIR, 'logs', 'django.log'),
},
},
'loggers': {
'django': {
'handlers': ['file', 'console'],
'level': 'DEBUG',
},
'django.template': {
'handlers': ['file', 'console'],
'level': 'INFO',
},
'App': {
'handlers': ['file', 'console'],
'level': 'DEBUG',
},
},
}
有一个我无法解释的行为:如果我运行,debug=True
我可以看到所有 SQL 查询都记录到控制台,但是当debug=False
这种情况没有发生时,即使我没有更改上面的配置。
为什么是这样?如何在我的日志记录配置中确定 SQL 查询是否记录到控制台?
解决方案
随着 Django 根据计算属性的真实性包装数据库游标,查询日志记录变得更深入。
从第 226 行开始,django.db.backends.base.base v2.2.6 来源
def _prepare_cursor(self, cursor):
"""
Validate the connection is usable and perform database cursor wrapping.
"""
self.validate_thread_sharing()
if self.queries_logged:
wrapped_cursor = self.make_debug_cursor(cursor)
else:
wrapped_cursor = self.make_cursor(cursor)
return wrapped_cursor
此计算属性将决定在何处强制调试或在项目设置中启用调试
从第 149 行开始,django.db.backends.base.base v2.2.6 来源
@property
def queries_logged(self):
return self.force_debug_cursor or settings.DEBUG
您应该能够获得默认连接的代理并强制使用调试光标。
from django.db import connection
connection.force_debug_cursor = True
但是,我建议不要使用这种方法,并支持在数据库中进行查询审计。
推荐阅读
- excel - 在 Excel 中加入(匹配)多个列
- javascript - 为什么在 React Hooks 中排序后数组不更新?
- sql - SQL Column ID值跳跃10000次
- arrays - Range 类的 AutoFilter 方法失败 - Array <> NOT EQUAL
- python - Python列表到文本文件并返回到列表
- java - 无法将日期和字符串对象的值打印到 glassfish 服务器的控制台
- c# - 返回具有不同泛型类型的泛型接口实现
- kubernetes - GCP Kubernetes 对象监控选项
- audio - HTML5 音频的下载按钮
- java - 使用 eclipse buildship 创建的新项目配置不正确(无法识别包)