16

I'm working on a web app in Python with Heroku and I can't figure out how to effectively test debug it. I tried using print(...) and sys.stdout.write(...) but I never see any output when I run locally with 'foreman start' or when I deploy to the cloud and run 'heroku logs' to see cloud logs. Furthermore, I can't figure out how to debug python runtime errors such as when an exception occurs. The web request for the app returns an HTTP 500 but I have no way of debugging that to see where the exception originated. Is there any way to see this information?

broseflip
  • 231
  • 2
  • 3
  • 6
  • 1
    Anything written to stdout should be captured in your logs. – Erik Sep 20 '12 at 03:25
  • @Erik What about stderr? [This question](http://stackoverflow.com/questions/11866322/heroku-logs-for-django-projects-missing-errors) seems to indicate heroku has trouble with stderr. – B Robster Feb 27 '13 at 01:37

3 Answers3

19

Adding sys.stdout.flush() after print statements solved this problem for me.

In my case, the problem seemed to be that stdout is buffered whereas stderr is not.

If you're not even seeing exceptions via foreman start, make sure you're actually hitting your server at the right IP/PORT. You should see HTTP access entries (e.g., GET /index.html) in the output from foreman start.

Also, you might try telling your web framework to run in debug mode—most modern frameworks will show stacktraces in the browser in debug/dev mode. Using Flask? app.config['DEBUG'] = True or app.run(..., debug=True).

# logging helper
def p(*args):
  print args[0] % (len(args) > 1 and args[1:] or [])
  sys.stdout.flush()
cameronboehmer
  • 435
  • 2
  • 8
15

If you are using Foreman to run a Python project, and you're having trouble seeing stdout/stderr, here are some solutions for you. If you are using a Procfile to invoke the python CLI directly, then you can use the '-u' option to avoid stdout buffering:

python -u script.py

If you are using a Procfile to manage a WSGI server, such as invoking gunicorn, flask, bottle, eve, etc., then you can add a ".env" file to the root of your python project, containing the following:

PYTHONUNBUFFERED=True

Also see the answers to this question: foreman only shows line with “started wit pid #” and nothing else

Community
  • 1
  • 1
jsears
  • 4,511
  • 2
  • 31
  • 36
12

Note to any other Django/Python beginngers. Remember to add

import sys

and the something like this

print ("hello world") # python 3
sys.stdout.flush()

will print to console.

Moving from PHP to Py/Dj KISS can be rare.

Marc
  • 1,895
  • 18
  • 25