Phil Cote Phil Cote - 4 months ago 37
Python Question

Flask application traceback doesn't show up in server log

I'm running my Flask application with uWSGI and nginx. There's a 500 error, but the traceback doesn't appear in the browser or the logs. How do I log the traceback from Flask?

uwsgi --http-socket --wsgi-file /var/webapps/magicws/ --module service:app --uid www-data --gid www-data --logto /var/log/magicws/magicapp.log

The uWSGI log only shows the 500 status code, not the traceback. There's also nothing in the nginx log.

[pid: 18343|app: 0|req: 1/1] () {34 vars in 642 bytes}
[Tue Sep 22 15:50:52 2015]
GET /getinfo?color=White => generated 291 bytes in 64 msecs (HTTP/1.0 500)
2 headers in 84 bytes (1 switches on core 0)

lv9 lv9

Run in debug mode by adding this line before gets called

app.debug = true

or by running with

Now a stack trace should appear in the terminal and the browser instead of a generic 500 error page.

When using the new flask command to run the server, set the environment variable FLASK_DEBUG.

FLASK_DEBUG=1 flask run

In production, you don't want to run your app in debug mode. Instead you should log the errors to a file.

Flask uses the standard Python logging library can be configured to log errors. Insert the the following to have send Flask's log messages to a file.

import logging
handler = logging.FileHandler('/path/to/app.log')  # errors logged to this file
handler.setLevel(logging.ERROR) # only log errors and above
app.logger.addHandler(handler)  # attach the handler to the app's logger

Read more about the Python logging module. In particular you may want to switch the file handler to a RotatingFileHandler to ensure log files don't grow too large. You may also want to change the logging level to record more than just errors.

Flask also has instructions on how to log your application.