Bagaimana untuk Melaksanakan Pengelogan Pertanyaan SQL Komprehensif dalam Django?

Barbara Streisand
Lepaskan: 2024-10-17 17:25:02
asal
477 orang telah melayarinya

How to Implement Comprehensive SQL Query Logging in Django?

Comprehensive SQL Query Logging in Django

Capturing all SQL queries executed by your Django application is crucial for debugging, performance analysis, and security audits. Here's a comprehensive guide to achieve this:

Modify your settings.py file and merge the following snippet into the LOGGING field:

<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>
Salin selepas log masuk

This configuration routes all Django database backend messages (SQL queries) to the console handler. By default, this will only be visible when DEBUG mode is enabled.

To capture all SQL statements in a file named all-sql.log, you can add the following configuration:

<code class="python">HANDLERS = {
    ...  # existing handlers

    'file': {
        'level': 'DEBUG',
        'class': 'logging.FileHandler',
        'filename': '/path/to/all-sql.log',  # adjust file path as needed
    }
}</code>
Salin selepas log masuk

Finally, add the new file handler to the loggers configuration:

<code class="python">LOGGERS = {
    ...  # existing loggers

    'django.db.backends': {
        'level': 'DEBUG',
        'handlers': ['console', 'file'],  # add 'file' handler
    }
}</code>
Salin selepas log masuk

With these changes, all SQL queries will be logged to both the console (when DEBUG is enabled) and the specified file. Adjust the file path in the filename parameter to suit your needs. Restart your Django application to enable the logging functionality.

Atas ialah kandungan terperinci Bagaimana untuk Melaksanakan Pengelogan Pertanyaan SQL Komprehensif dalam Django?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!