【发布时间】:2018-12-18 12:07:47
【问题描述】:
可能我不太了解日志记录在 Python 中的实际工作原理。我正在尝试调试一个 Flask+SQLAlchemy(但没有 flask_sqlalchemy)应用程序,该应用程序只有在从 Apache 中运行时才会神秘地挂在某些查询上,所以我需要有适当的日志记录才能获得有意义的信息。 Flask 应用程序默认带有一个不错的记录器+处理程序,但我如何让 SQLAlchemy 使用相同的记录器?
SQLAlchemy 中的“配置日志记录”部分仅说明了如何打开一般的日志记录,而不是如何将 SQLAlchemy 的日志记录输出“连接”到现有的记录器。
我一直在看着Flask + sqlalchemy advanced logging 有一段时间,一脸茫然,没有表情。我不知道我的问题的答案是否在那里。
编辑:感谢给出的答案,我现在知道我可以让两个记录器使用同一个处理程序。当然,现在我的 apache 错误日志中充斥着数百行回显的 SQL 调用。我只想将错误消息记录到 httpd 日志中,并将所有较低级别的内容转移到单独的日志文件中。请参阅下面的代码。但是,我仍然将每条调试消息都放入 http 日志中。为什么?
if app.config['DEBUG']:
# Make logger accept all log levels
app.logger.setLevel(logging.DEBUG)
for h in app.logger.handlers:
# restrict logging to /var/log/httpd/error_log to errors only
h.setLevel(logging.ERROR)
if app.config['LOGFILE']:
# configure debug logging only if logfile is set
debug_handler = logging.FileHandler(app.config['LOGFILE'])
debug_handler.setLevel(logging.DEBUG)
app.logger.addHandler(debug_handler)
# get logger for SQLAlchemy
sq_log = logging.getLogger('sqlalchemy.engine')
sq_log.setLevel(logging.DEBUG)
# remove any preconfigured handlers there might be
for h in sq_log.handlers:
sq_log.removeHandler(h)
h.close()
# Now, SQLAlchemy should not have any handlers at all. Let's add one
# for the logfile
sq_log.addHandler(debug_handler)
【问题讨论】:
标签: python flask sqlalchemy