如何使用Flask在Heroku中显示stdout日志?

时间:2019-01-21 20:17:31

标签: python heroku flask gunicorn procfile

在我的Python 3.7.1应用程序中,我正在使用Flask并将其部署到Heroku,并且除登录到Heroku控制台外,其他一切都正常。我一直在寻找答案,并以为我找到了一些……但是,遗憾的是,它们最终并没有输出到Heroku Log Console。当我在本地运行该应用程序时,使用“ 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进行修改,但是我不确定是什么。有人可以提出任何建议吗?

1 个答案:

答案 0 :(得分:0)

我通过将以下内容添加到我的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的答案