Created
February 13, 2021 08:25
-
-
Save conformist-mw/4e174da8a39d0e7b4a2f408729f0d227 to your computer and use it in GitHub Desktop.
This file contains 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
import logging | |
class SQLFormatter(logging.Formatter): | |
""" | |
https://markusholtermann.eu/2016/01/syntax-highlighting-for-djangos-sql-query-logging/ | |
""" | |
def format(self, record): | |
# Check if Pygments is available for coloring | |
try: | |
import pygments | |
from pygments.lexers import SqlLexer | |
from pygments.formatters import Terminal256Formatter | |
except ImportError: | |
pygments = None | |
# Check if sqlparse is available for indentation | |
try: | |
import sqlparse | |
except ImportError: | |
sqlparse = None | |
# Remove leading and trailing whitespaces | |
sql = record.sql.strip() | |
if sqlparse: | |
# Indent the SQL query | |
sql = sqlparse.format(sql, reindent=True) | |
if pygments: | |
# Highlight the SQL query | |
# Available colors http://help.farbox.com/pygments.html | |
sql = pygments.highlight( | |
sql, | |
SqlLexer(), | |
Terminal256Formatter(style='borland') | |
) | |
# Set the record's statement to the formatted query | |
record.statement = sql | |
return super(SQLFormatter, self).format(record) | |
LOGGING = { | |
'version': 1, | |
'disable_existing_loggers': False, | |
'formatters': { | |
'sql': { | |
'()': SQLFormatter, | |
'format': '[%(duration).3f] %(statement)s', | |
} | |
}, | |
'handlers': { | |
'console': { | |
'level': 'DEBUG', | |
'class': 'logging.StreamHandler', | |
}, | |
'sql': { | |
'class': 'logging.StreamHandler', | |
'formatter': 'sql', | |
'level': 'DEBUG', | |
} | |
}, | |
'loggers': { | |
'django.db.backends': { | |
'handlers': ['sql'], | |
'level': 'DEBUG', | |
'propagate': False, | |
}, | |
'django.db.backends.schema': { | |
'handlers': ['console'], | |
'level': 'DEBUG', | |
'propagate': False, | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment