5

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)
4

2 回答 2

6

尝试这样的事情(未经测试):

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)

您所做的只是创建一个不同的记录器,这样它们就不会混淆,这应该可以解决您遇到的问题:)

于 2013-06-13T10:28:51.763 回答
5

Sqlalchemy 使用“sqlalchemy.engine”记录器。要配置它,您可以执行以下操作:

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

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

lg.add_handler(lh)

之后,您可以使用

logging.getLogger('sqlalchemy.engine')
logging.info('your sql statement')
于 2013-06-13T10:55:46.470 回答