Skip to content

Instantly share code, notes, and snippets.

@neilpanchal
Created March 31, 2020 20:29
Show Gist options
  • Save neilpanchal/b19f275d5e859ac814b265e15b08021a to your computer and use it in GitHub Desktop.
Save neilpanchal/b19f275d5e859ac814b265e15b08021a to your computer and use it in GitHub Desktop.
SQL Query Log Formatter
import logging
import sqlparse
class SQLFileHandler(logging.FileHandler):
def emit(self, record):
try:
record.msg = sqlparse.format(record.msg, reindent=True, keyword_case='upper')
except Exception:
pass
super().emit(record)
# Get logger
sql_logger = logging.getLogger('sqlalchemy.engine')
# Attach adapter
# Set level
sql_logger.setLevel(logging.INFO)
# Log formatter
log_formatter = logging.Formatter('[%(asctime)s] %(levelname)s: \n%(message)s')
file_handler = SQLFileHandler('logs/mylog.log')
file_handler.setFormatter(log_formatter)
sql_logger.addHandler(file_handler)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment