How Can I Log All SQL Queries in Django?

Patricia Arquette
Release: 2024-10-17 17:27:03
Original
468 people have browsed it

How Can I Log All SQL Queries in Django?

Logging SQL Queries in Django

This question seeks a method to record all SQL queries executed by a Django application, including those originating from the admin site. The task is to create a central log file (e.g., all-sql.log) to capture these SQL statements.

Configuring LOGGING:

To achieve this, merge the following snippet with the LOGGING field in your settings.py:

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

Explanation:

  • Set 'level': 'DEBUG' to capture all SQL queries, regardless of their severity.
  • Use 'handlers': ['console'] to redirect SQL queries to the console output.
  • Configure 'loggers': {'django.db.backends': {'level': 'DEBUG'}} to log all SQL queries executed through the Django ORM.

Note:

This solution originated from @acardenas89's answer. It ensures that all Django-executed SQL queries are written to the console when the application is in debug mode.

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

source:php
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