首页 > 解决方案 > 如何使用 Flask 在 Heroku 中显示标准输出日志?

问题描述

在我的 Python 3.7.1 应用程序中,我使用 Flask 并将其部署到 Heroku,一切正常,除了登录到 Heroku 控制台。我已经搜索了答案,并认为我找到了一些……但可惜他们最终没有打印到 Heroku 日志控制台。当我在本地运行应用程序时,使用“py app.py”它显示得很好。

在我的 Procfile 中,我有以下内容:

web: gunicorn app:app --log-level debug --log-file=-

在我的 app.py 文件中,我有以下内容:

if __name__ == '__main__':
    formatter = logging.Formatter( "%(asctime)s | %(pathname)s:%(lineno)d | %(funcName)s | %(levelname)s | %(message)s ")
    handler = RotatingFileHandler('logs/SlackBotApp.log', maxBytes=10000, backupCount=5)
    handler.setLevel(logging.DEBUG)
    handler.setFormatter(formatter)

    app.logger.addHandler(handler)
    app.logger.addHandler(logging.StreamHandler(stream=sys.stdout))
    app.logger.setLevel(logging.DEBUG)

    app.run()

我像这样调用记录器:

app.logger.info("Url Requested: {}".format(url))

我觉得我需要对我的 Procfile 进行修改,但我不确定是什么。任何人都可以提出任何建议吗?

标签: pythonherokuflaskgunicornprocfile

解决方案


我通过将以下内容添加到我的 app.py 中解决了这个问题:

if __name__ != '__main__':
    gunicorn_logger = logging.getLogger('gunicorn.error')
    app.logger.handlers = gunicorn_logger.handlers
    app.logger.setLevel(gunicorn_logger.level)

并将我的 Procfile 调整为:

web: gunicorn app:app --log-level=debug

感谢https://medium.com/@trstringer/logging-flask-and-gunicorn-the-manageable-way-2e6f0b8beb2f的回答


推荐阅读