如何记录sqlalchemy中返回的SQL语句和行以帮助调试?

时间:2015-01-02 20:19:32

标签: debugging logging sqlalchemy

如何配置sqlalchemy以记录它对数据库服务器发出的SQL语句,还记录从这些语句返回的行?这对调试很有用。

1 个答案:

答案 0 :(得分:1)

选项1:将sqlalchemy.engine记录器日志级别设置为logging.INFOlogging.DEBUG 如,

>>> import logging
>>> logging.basicConfig()
>>> logger = logging.getLogger('sqlalchemy.engine')
>>> log.setLevel(logging.DEBUG)
>>> session.query(User).all()
2015-01-02 11:54:25,854 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-01-02 11:54:25,856 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name
FROM users
2015-01-02 11:54:25,857 INFO sqlalchemy.engine.base.Engine {}
2015-01-02 11:54:25,858 DEBUG sqlalchemy.engine.base.Engine Col ('users_id', 'users_name')
2015-01-02 11:54:25,860 DEBUG sqlalchemy.engine.base.Engine Row (1, u'Alice')
2015-01-02 11:54:25,860 DEBUG sqlalchemy.engine.base.Engine Row (2, u'Bob')

参考:Configuring Logging

选项2:在致电echo时使用sqlalchemy.create_engine() arg:

如,

>>> from sqlalchemy import create_engine
>>> from sqlalchemy.orm import sessionmaker
>>> engine = create_engine('postgres://postgres_user:my_password@localhost/my_db',
...                        echo="debug")
>>> Session = sessionmaker(bind=engine)
>>> session = Session()
>>> users = session.query(User).all()
2015-01-02 11:54:25,854 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
2015-01-02 11:54:25,856 INFO sqlalchemy.engine.base.Engine SELECT users.id AS users_id, users.name AS users_name
FROM users
2015-01-02 11:54:25,857 INFO sqlalchemy.engine.base.Engine {}
2015-01-02 11:54:25,858 DEBUG sqlalchemy.engine.base.Engine Col ('users_id', 'users_name')
2015-01-02 11:54:25,860 DEBUG sqlalchemy.engine.base.Engine Row (1, u'Alice')
2015-01-02 11:54:25,860 DEBUG sqlalchemy.engine.base.Engine Row (2, u'Bob')

Per the sqlalchemy documentation:

  

* sqlalchemy。 create_engine (* args,** kwargs)
  ...
   echo = False - 如果为True,Engine会将所有语句及其参数列表的repr()记录到引擎记录器,默认为sys.stdout。可以随时修改Engine的echo属性以打开和关闭日志记录。如果设置为字符串“debug”,结果行也将打印到标准输出。