Created
March 31, 2020 20:29
-
-
Save neilpanchal/b19f275d5e859ac814b265e15b08021a to your computer and use it in GitHub Desktop.
SQL Query Log Formatter
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 | |
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