How to output SQLAlchemy logger only to a file?

2,013 views
Skip to first unread message

r...@rosenfeld.to

unread,
Mar 19, 2015, 7:25:33 PM3/19/15
to sqlal...@googlegroups.com

From what I read in the SQLAlchemy logging configuration documentation, I understood that the echo argument on sqlalchemy.create_engine controls whether sqlalchemy logging is forced to stdout, but shouldn't affect whether log messages are available to log handlers.

In the code below, I get no output to stdout OR db.log if echo=False and I get output to both stdout AND db.log if echo=True. I want nothing to stdout while db.log is still populated. How can I accomplish that?

This is python 2.7.6 and sqlalchemy 0.9.9

import sqlalchemy
import logging

active_db_url = 'postgres://user:pass@localhost/log_test'

db_log_file_name = 'db.log'
db_log_level = logging.INFO

db_handler = logging.FileHandler(db_log_file_name)
db_handler.setLevel(db_log_level)

db_logger = logging.getLogger('sqlalchemy')
db_logger.addHandler(db_handler)

engine = sqlalchemy.create_engine(active_db_url, echo=True)
engine.connect()


Cross posted from http://stackoverflow.com/questions/29114627/how-to-output-sqlalchemy-logger-only-to-a-file 

Thanks in advance,

Rob

Michael Bayer

unread,
Mar 19, 2015, 7:33:27 PM3/19/15
to sqlal...@googlegroups.com


r...@rosenfeld.to wrote:

> From what I read in the SQLAlchemy logging configuration documentation, I understood that the echo argument on sqlalchemy.create_engine controls whether sqlalchemy logging is forced to stdout, but shouldn't affect whether log messages are available to log handlers.
>
> In the code below, I get no output to stdout OR db.log if echo=False and I get output to both stdout AND db.log if echo=True. I want nothing to stdout while db.log is still populated. How can I accomplish that?

Hmm well logging is looking at the effective level of the logger
itself, not the handler, so you’d need db_logger.setLevel(db_log_level). I
think the “level” that’s on the handler is an additional level of filtering.

The effective level of a logger you can see like this:

>>> import logging
>>> log = logging.getLogger("asdf")
>>> log.getEffectiveLevel()
30

which we can see is WARN:

>>> logging.WARN, logging.INFO, logging.DEBUG
(30, 20, 10)


the “echo=True” flag sets up this level if not set already.
> --
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sqlalchemy+...@googlegroups.com.
> To post to this group, send email to sqlal...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sqlalchemy.
> For more options, visit https://groups.google.com/d/optout.

r...@rosenfeld.to

unread,
Mar 19, 2015, 7:38:49 PM3/19/15
to sqlal...@googlegroups.com
Thanks much.  That was it.
Reply all
Reply to author
Forward
0 new messages