Home > Database > Mysql Tutorial > How Can I Log All Django SQL Queries, Including Admin Queries, for Debugging and Monitoring?

How Can I Log All Django SQL Queries, Including Admin Queries, for Debugging and Monitoring?

Linda Hamilton
Release: 2025-01-15 21:14:52
Original
128 people have browsed it

How Can I Log All Django SQL Queries, Including Admin Queries, for Debugging and Monitoring?

Interception and logging of all Django SQL queries

Question:

Logging of all SQL queries executed by a Django application is valuable for debugging, performance analysis, and security monitoring. How can this be achieved, including every SQL statement generated by the Django admin interface?

Solution:

To log all SQL queries, enhance the LOGGING configuration in settings.py with the following directive:

<code>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>
Copy after login

Instructions:

This configuration adds a new handler called "console" that prints log messages to the console, but only when DEBUG mode is enabled. The 'django.db.backends' logger is configured to log all SQL queries at DEBUG level to this handler.

Usage:

To write all SQL queries to a file instead of the console, modify the "handlers" section as follows:

<code>'handlers': {
    'file': {
        'level': 'DEBUG',
        'filters': ['require_debug_true'],
        'class': 'logging.FileHandler',
        'filename': '/path/to/all-sql.log',
    }
}</code>
Copy after login

This will redirect all debug logs (including SQL queries) to the specified file.

The above is the detailed content of How Can I Log All Django SQL Queries, Including Admin Queries, for Debugging and Monitoring?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template