如何使用 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进行修改,但我不确定是什么。任何人都可以提出任何建议吗?

我通过在 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 的回答

最新更新