Search code examples
pythonloggingsqlalchemypyramidpylons

Logging to SQLAlchemy logger in Pyramid app


I have defined SQA logger in development.ini to log SQA queries to a separate file like this:

[handler_sqa]
class = FileHandler
args = ('%(here)s/log/sqlalchemy.log','a')
# "level = INFO" logs SQL queries.
# "level = DEBUG" logs SQL queries and results.
# "level = WARN" logs neither.  (Recommended for production systems.)
level = INFO
formatter = generic    


[logger_sqlalchemy]
level = INFO
handlers = sqa
qualname = sqlalchemy.engine.base.Engine
propagate = 0

Now, it works, that is, SQA logs to that file only.

However, I would also like this specific logger to log additional messages to SQA log, i.e. to file log/sqlalchemy.log. I can get what seems to be the SQA logger like so:

sqa_log = logging.getLogger('logger_sqlalchemy')

However, it logs to main (that is root) logger instead..

How can I log additional messages to SQA logger instance instead of root logger?


Solution

  • The logger is is configured to handle anything with the prefix sqlalchemy.engine.base.Engine. Therefore you could make a new logger logging.getLogger('sqlalchemy.engine.base.Engine.foo') but that would be poor practice I think to hijack the sqlalchemy namespace for your own purposes. Alternatively I think you should define a different logger that also shares the sqa handler.

    [handler_sqa]
    # all the same
    
    [logger_myown]
    handlers = sqa
    propagate = 0
    qualname = mysqa
    

    You can grab that new logger via logging.getLogger('mysqa').