如何在 Django 中捕獲所有 SQL 查詢以進行調試和效能分析?

Patricia Arquette
發布: 2024-10-17 17:28:30
原創
503 人瀏覽過

How to Capture All SQL Queries in Django for Debugging and Performance Analysis?

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.

以上是如何在 Django 中捕獲所有 SQL 查詢以進行調試和效能分析?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板