SQLAlchemy中的友好查询日志记录

从用户的角度来看,SQLAlchemy的查询日志记录似乎有点过于冗长甚至有些神秘:

2015-10-02 13:51:39,500 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-10-02 13:51:39,502 INFO sqlalchemy.engine.base.Engine SELECT anon_1.shelves_title AS anon_1_shelves_title, ..., anon_1.shelves_created_at AS anon_1_shelves_created_at, anon_1.shelves_updated_at AS anon_1_shelves_updated_at, products_1.id AS products_1_id, products_1.title AS products_1_title
FROM (SELECT shelves.title AS shelves_title, ..., shelves.created_at AS shelves_created_at, shelves.updated_at AS shelves_updated_at
FROM shelves
WHERE shelves.title = ?
 LIMIT ? OFFSET ?) AS anon_1 LEFT OUTER JOIN products AS products_1 ON anon_1.shelves_title = products_1.shelf_title
2015-10-02 13:51:39,502 INFO sqlalchemy.engine.base.Engine ('sample', 1, 0)
2015-10-02 13:51:39,503 INFO sqlalchemy.engine.base.Engine ROLLBACK

(不一定具有代表性,但希望足以说明问题)

可以说Ruby on Rails在这里是一个很好的参考,提供了实际数据库查询的简洁和彩色输出:

《SQLAlchemy中的友好查询日志记录》

(通过https://code.google.com/p/pylonsquerybar/#What_Others_Have_Done)

有没有一种简单的方法来获得SQLAlchemy的类似输出? (前面提到的Pylons查询栏似乎不是为了框架无关的重用而设计的.)

最佳答案 你可以设置任何格式的记录器,你可以得到记录器:

import logging
logging.basicConfig(filename='db.log')
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

如何设置颜色和格式请看这里:
How can I color Python logging output?

点赞