Home >Database >Mysql Tutorial >How to Effectively Log SQL Queries in Django?
Detailed explanation of Django SQL query logging
Django is a popular Python web framework for building database-driven applications. To ensure optimal performance and troubleshoot database issues, it is often necessary to log all SQL queries executed by an application. This guide will walk you through step-by-step how to implement this logging in Django.
Location query logging code
To log SQL queries, you need to edit your Django project's settings.py
file. In this file, find the LOGGING
dictionary and modify it according to the following code snippet:
<code class="language-python">LOGGING = { 'version': 1, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', } }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', } }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['console'], } } }</code>
Integrated logging configuration
After merging the provided code snippet with the LOGGING
dictionary, Django will automatically log all SQL queries to the console. To redirect queries to a separate file (e.g. all-sql.log
), you need to add a file handler to the handlers
section. The following is an example of the modified configuration:
<code class="language-python">LOGGING = { 'version': 1, 'filters': { 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', } }, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.StreamHandler', }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/path/to/all-sql.log', # 请替换为您的日志文件路径 } }, 'loggers': { 'django.db.backends': { 'level': 'DEBUG', 'handlers': ['file'], } } }</code>
Remember to replace /path/to/all-sql.log
with your actual log file path. After configuration is complete, all database queries will be logged to the specified file.
The above is the detailed content of How to Effectively Log SQL Queries in Django?. For more information, please follow other related articles on the PHP Chinese website!