Python mod_wsgi 写入自定义日志文件而不是 apache error_log

标签 python apache flask mod-wsgi

我有一个 Python 应用程序,它使用 Apache 和 mod_wsgi 部署在生产环境中。 在我的应用程序中,我设置了日志记录,如下所示:

配置文件:

log_file = os.path.dirname(os.path.abspath(__file__)) + "/app.log"
log_level = logging.DEBUG

__init__.py 文件:

root_logger = logging.getLogger()
root_logger.setLevel(config.log_level)

log_format = logging.Formatter("%(asctime)s [%(levelname)s] [%(name)s] %(message)s")

file_handler = logging.FileHandler(config.log_file)
file_handler.setFormatter(log_format)

stream_handler = logging.StreamHandler()
stream_handler.setFormatter(log_format)

root_logger.addHandler(file_handler)
root_logger.addHandler(stream_handler)

此代码在创建 Flask 应用程序之前执行。

所有非错误/异常的日志记录都会正确记录到此自定义文件中。

但是,如果在 Web 服务器运行时生成异常,则错误会写入 Apache 的错误日志,而不是写入此处配置的错误日志。如何配置Python的logging/mod_wsgi/Apache,以便将所有内容写入此处配置的日志文件中?

最佳答案

将您的记录器添加到 WSGI 应用程序记录器,来自 flask error handling docs :

if not app.debug:
    import logging
    from themodule import TheHandlerYouWant
    file_handler = TheHandlerYouWant(...)
    file_handler.setLevel(logging.WARNING)
    app.logger.addHandler(file_handler)

关于Python mod_wsgi 写入自定义日志文件而不是 apache error_log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26018565/

相关文章:

python - 为什么我指定的 flask 单元测试不使用临时文件数据库?

python-3.x - Flask-migrate:更改模型属性并重命名相应的数据库列

python - gae python ascii编解码器无法解码字节

python - Django聚合外键的最高值

python - python功能可以足够聪明地显示其功能吗?

python - 如何在 Django Rest Framework 中使用自定义 token 模型

java - 从 Apache Http 客户端迁移到 OkHttp

linux - 如何获取服务器的点击数

linux - 如何将 Linux Centos 6.5 服务器上 Apache Tomcat 上的端口 8080 更改为默认端口?

flask - 使用一对多关系过滤 flask 管理中的列值