Logging All SQL Queries in Django
In Django, capturing the SQL queries executed by your application can provide invaluable insights for debugging, performance analysis, and security monitoring. Here's how you can accomplish this:
To log all SQL queries, including those from the admin site, modify the LOGGING configuration in your settings.py file. Add the following snippet to merge with the existing LOGGING field:
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'], } } }
This configuration will route all SQL queries to the console when the DEBUG flag is set to True in your settings.py. If you prefer to log the queries to a file, you can replace the 'console' handler with a 'FileHandler' and specify the path to the log file.
For example, to log the queries to a file named all-sql.log, use the following handler:
'handlers': { 'all_sql_file': { 'level': 'DEBUG', 'filters': ['require_debug_true'], 'class': 'logging.FileHandler', 'filename': 'all-sql.log', } }
Make sure to restart your Django server after making these changes to ensure that the new logging configuration takes effect.
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!