Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pycharm duplicated log for SQLALCHEMY_ECHO = True

When I want to log sqlalchemy queries by setting SQLALCHEMY_ECHO = True in my flask app I am getting duplicated log in console. Once with red color then once with white. How can I get single color? enter image description here

like image 876
IamMashed Avatar asked Nov 02 '25 03:11

IamMashed


1 Answers

This most probably happens because SQLAlchemy adds their own handlers to their loggers in sqlalchemy.log.InstanceLogger.__init__:

    def __init__(self, echo: _EchoFlagType, name: str):
        self.echo = echo
        self.logger = logging.getLogger(name)

        # if echo flag is enabled and no handlers,
        # add a handler to the list
        if self._echo_map[echo] <= logging.INFO and not self.logger.handlers:
            _add_default_handler(self.logger)  # <=== Handler is added here

But the logger still propagates log record to the higher level loggers and their attached handlers. So if you have a handler attached to your root logger then the log record will be printed from both the handler attached by SQLAlchemy and the root logger's handler(s).

SQLAlchemy developers should have instead attached their handler to root logger and only in case if there are no other handlers attached already. Similar to standard library logging.basicConfig() behavior.

This is how I work around it:

from sqlalchemy import log as sqlalchemy_log
sqlalchemy_log._add_default_handler = lambda x: None  # Patch to avoid duplicate logging
like image 180
Dmitry Mugtasimov Avatar answered Nov 04 '25 11:11

Dmitry Mugtasimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!