Created
July 22, 2019 15:23
-
-
Save Sinkler/a3108648b3aa4f867681ec11ac1b4529 to your computer and use it in GitHub Desktop.
Show SQL traceback in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if os.environ.get('DEBUG_SQL') or os.environ.get('DEBUG_SQL_TRACEBACK'): | |
LOGGING['loggers']['django.db.backends'] = { | |
'level': 'DEBUG', | |
'handlers': ['console'], | |
'propagate': False, | |
} | |
if os.environ.get('DEBUG_SQL_TRACEBACK'): | |
import traceback | |
import logging | |
import django.db.backends.utils as bakutils | |
logger = logging.getLogger('django.db.backends') | |
cursor_debug_wrapper_orig = bakutils.CursorDebugWrapper | |
def print_stack_in_project(sql): | |
stack = traceback.extract_stack() | |
for path, lineno, func, line in stack: | |
if 'lib/python' in path or 'settings.py' in path: | |
continue | |
logger.debug(f'File "{path}", line {lineno}, in {func}') | |
logger.debug(f' {line}') | |
logger.debug(sql) | |
logger.debug('\n') | |
class CursorDebugWrapperLoud(cursor_debug_wrapper_orig): | |
def execute(self, sql, params=None): | |
try: | |
return super().execute(sql, params) | |
finally: | |
sql = self.db.ops.last_executed_query(self.cursor, sql, params) | |
print_stack_in_project(sql) | |
def executemany(self, sql, param_list): | |
try: | |
return super().executemany(sql, param_list) | |
finally: | |
print_stack_in_project(sql) | |
bakutils.CursorDebugWrapper = CursorDebugWrapperLoud |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment