如何在python中查看Heroku日志记录和运行时错误输出

bro*_*lip 11 python web-applications heroku

我正在使用Heroku开发Python的Web应用程序,我无法弄清楚如何有效地测试它.我尝试使用print(...)和sys.stdout.write(...),但是当我使用'foreman start'本地运行或者当我部署到云并运行'heroku logs'来查看时,我从未看到任何输出云日志.此外,我无法弄清楚如何调试python运行时错误,例如发生异常时.该应用程序的Web请求返回HTTP 500,但我无法调试它以查看异常发生的位置.有没有办法看到这些信息?

cam*_*mer 15

sys.stdout.flush()在打印语句之后添加为我解决了这个问题.

在我的情况下,问题似乎是stdout被缓冲而stderr没有.

如果您甚至没有看到异常foreman start,请确保您实际上是在正确的IP/PORT上访问您的服务器.您应该在输出中看到HTTP访问条目(例如,GET /index.html)foreman start.

此外,您可能会尝试告诉您的Web框架在调试模式下运行 - 大多数现代框架将在调试/开发模式下在浏览器中显示堆栈跟踪.使用烧瓶?app.config['DEBUG'] = Trueapp.run(..., debug=True).

# logging helper
def p(*args):
  print args[0] % (len(args) > 1 and args[1:] or [])
  sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)


jse*_*ars 14

如果您使用Foreman运行Python项目,并且您在查看stdout/stderr时遇到问题,那么这里有一些解决方案.如果您使用Procfile直接调用python CLI,那么您可以使用'-u'选项来避免stdout缓冲:

python -u script.py
Run Code Online (Sandbox Code Playgroud)

如果您使用Procfile来管理WSGI服务器,例如调用gunicorn,flask,bottle,eve等,那么您可以将".env"文件添加到python项目的根目录,其中包含以下内容:

PYTHONUNBUFFERED=True
Run Code Online (Sandbox Code Playgroud)

另请参阅这个问题的答案: 工头只显示"启动机智pid#"的行,而没有别的


Mar*_*arc 7

任何其他Django/Python初学者的注意事项.记得加

import sys
Run Code Online (Sandbox Code Playgroud)

和这样的事情

print ("hello world") # python 3
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

将打印到控制台.

从PHP迁移到Py/Dj KISS可能很少见.