Question

I'm using flask and werkzeug. To monitor sql statements emitted from sqlalchemy I've set up a logging.basicConfig() logger and attached the before_cursor_execute event to monitor SQL statements. But now werkzeug also attaches the logging to that logger, that's not what I want. so my log looks like this...(the werkzeug message is not wanted)

INFO:root:SELECT anon_1.heartbeat_id AS anon_1_heartbeat_id
FROM (SELECT heartbeat.id AS heartbeat_id FROM heartbeat ORDER BY stamp desc LIMIT ?
OFFSET ?) AS anon_1 ORDER BY heartbeat_name
INFO:werkzeug:127.0.0.1 - - [13/Jun/2013 12:10:52] "GET / HTTP/1.1" 200 -

In the werkzeug documentation I can't find anything about logging. And here is the code I'm using.

logging.basicConfig(filename='sql.log', level=logging.INFO)
def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    logging.info(statement)
event.listen(engine, "before_cursor_execute", before_cursor_execute)
Était-ce utile?

La solution

Try something like this instead (untested):

import logging
logger = logging.getLogger('sql')
logger.addHandler(logging.StreamHandler('sql.log'))
logger.setLevel(logging.INFO)

def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
    logger.info(statement)
event.listen(engine, "before_cursor_execute", before_cursor_execute)

What you do is simply create a different logger so they don't mix up, that should fix the problems you're having :)

Autres conseils

Sqlalchemy uses "sqlalchemy.engine" logger. To configure it, you can do the following:

lg = logging.getLogger('sqlalchemy.engine')
lg.setLevel(logging.INFO)

lh = logging.StreamHandler()
lh.setFormatter(logging.Formatter('YOUR FORMAT HERE'))

lg.add_handler(lh)

After that, you can use

logging.getLogger('sqlalchemy.engine')
logging.info('your sql statement')
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top