繁体   English   中英

如何让 SQLAlchemy 和 Flask 使用相同的记录器?

[英]How to make SQLAlchemy and Flask use the same logger?

可能我不太明白日志记录在 Python 中是如何工作的。 我正在尝试调试一个 Flask+SQLAlchemy(但没有flask_sqlalchemy)应用程序,该应用程序仅在从 Apache 内部运行时神秘地挂在某些查询上,所以我需要有适当的日志记录才能获得有意义的信息。 默认情况下,Flask 应用程序带有一个不错的记录器+处理程序,但是如何让 SQLAlchemy 使用相同的记录器?

SQLAlchemy 中的“配置日志记录”部分仅说明了如何打开日志记录,但没有说明如何将 SQLAlchemy 的日志记录输出“连接”到现有记录器。

我一直在看Flask + sqlalchemy 高级日志记录一段时间,面无表情。 我不知道我的问题的答案是否在那里。

编辑:感谢给出的答案,我现在知道我可以让两个记录器使用相同的处理程序。 当然,现在我的 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)

您不能make SQLAlchemy and Flask use the same logger ,但是可以通过添加公共Handler使它们写入一个位置。 也许这篇文章很有帮助: https : //www.electricmonk.nl/log/2017/08/06/understanding-pythons-logging-module/

顺便说一句,如果要在一个请求中获取所有日志,则可以在请求之前为当前线程设置唯一名称,然后在日志记录的格式化程序中添加threadName

在EDIT上回答我的问题:我仍然在create_engine上设置了“ echo = True”,所以我看到的是stderr上的所有其他输出。 echo = False停止了该操作,但仍记录到调试级别DEBUG。

清除 SqlAlchemy 创建的所有相应处理程序:

logging.getLogger("sqlalchemy.engine.Engine").handlers.clear()

上面的代码应该在引擎创建后调用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM