Program Tip

모든 SQL 쿼리 기록

programtip 2020. 10. 13. 19:05
반응형

모든 SQL 쿼리 기록


내 장고 애플리케이션이 수행 한 모든 SQL 쿼리를 어떻게 기록 할 수 있습니까?

관리 사이트의 SQL을 포함하여 모든 것을 기록하고 싶습니다. 내가 본 이 질문FAQ에 대답을 하지만, 난 여전히 내가 어디에 놓아야 알아낼 수 없습니다

from django.db import connection
connection.queries

모든 것을 하나의 파일에 기록하려면?

그래서 내 질문은-모든 SQL 문이 기록되는 파일 (예 : all-sql.log)을 가지려면 어떻게해야합니까?


https://github.com/django-debug-toolbar/django-debug-toolbar를 확인 하십시오.

주어진 페이지에서 생성 된 모든 쿼리를 볼 수 있습니다. 발생 위치 등의 스택 추적

편집 : 모든 SQL 쿼리를 파일 등에 기록하려면 미들웨어를 만들고 싶을 것입니다. 미들웨어는 모든 요청에서 실행됩니다. 이런 종류의 Django 스 니펫이 여러 개 있습니다.

그들은 터미널에 인쇄하는 것과 관련이 있지만 파이썬의 로깅 라이브러리를 사용하도록 조정하는 것은 어렵지 않습니다.


다음 코드 조각을의 LOGGING필드 와 병합 합니다 settings.py.

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'],
        }
    }
}

@ acardenas89 답변에서 조정


settings.py에 다음 굵은 문장을 추가하십시오.


디버그하는 경우 :
    가져 오기 로깅
    l = logging.getLogger ( 'django.db.backends')
    l.setLevel (logging.DEBUG)
    l.addHandler (logging.StreamHandler ())


로깅 = {
    '버전': 1,
    'disable_existing_loggers': False,
    '필터': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            '수준': '오류',
            '필터': [ 'require_debug_false'],
            '클래스': 'django.utils.log.AdminEmailHandler'
        }, '콘솔': {
            '레벨': '디버그',
            '클래스': 'logging.StreamHandler',
        } ,
    },
    '로거': {
        'django.request': {
            'handlers': [ 'mail_admins'],
            '수준': '오류',
            '전파': 참,
        }, 'django.db.backends.sqlite3': {
            '레벨': '디버그',
            '핸들러': [ '콘솔'],
        } ,
    }
}
  

자원 / 신용


Django 1.3은 모든 SQL 문을 django.db.backends 로거에 기록합니다.

https://docs.djangoproject.com/en/dev/topics/logging/#django-db-backends


To log SQL queries during testing, you need two things:

  1. django.db.backends logger enabled and
  2. @override_settings(DEBUG=True) decorator.

Test runner will set DEBUG=False by default, ignoring what you may have set in DJANGO_SETTINGS_MODULE.

The minimum settings:

# https://docs.djangoproject.com/en/dev/ref/settings/#logging
LOGGING = {
    'version': 1,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'level': 'DEBUG',
        },
    },
    'root': {
        'handlers': ['console'],
    }
}

The example test case:

from django.contrib.auth.models import User
from django.test import TestCase, override_settings


class UserTests(TestCase):

    # To log queries in tests you need to manually override DEBUG setting
    # because testing sets DEBUG=False by default

    @override_settings(DEBUG=True)
    def test_create_user(self):
        User.objects.create()

You need to put this in a middleware package. The middleware sits between the webserver/django core and all your views. It can do preprocessing before the request, and postprocessing after the request completed. For example, save the queries to a file.

참고URL : https://stackoverflow.com/questions/4375784/log-all-sql-queries

반응형