New in version 0.3.
Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail. Here are some situations where perfectly fine code can lead to server errors:
And that’s just a small sample of issues you could be facing. So how do we deal with that sort of problem? By default if your application runs in production mode, Flask will display a very simple page for you and log the exception to the
But there is more you can do, and we will cover some better setups to deal with errors.
Sending error mails, even if just for critical ones, can become overwhelming if enough users are hitting the error and log files are typically never looked at. This is why we recommend using Sentry for dealing with application errors. It’s available as an Open Source project on GitHub and is also available as a hosted version which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds.
To use Sentry you need to install the
$ pip install raven
And then add this to your Flask app:
from raven.contrib.flask import Sentry sentry = Sentry(app, dsn='YOUR_DSN_HERE')
Or if you are using factories you can also init it later:
from raven.contrib.flask import Sentry sentry = Sentry(dsn='YOUR_DSN_HERE') def create_app(): app = Flask(__name__) sentry.init_app(app) ... return app
YOUR_DSN_HERE value needs to be replaced with the DSN value you get from your Sentry installation.
Afterwards failures are automatically reported to Sentry and from there you can receive error notifications.
You might want to show custom error pages to the user when an error occurs. This can be done by registering error handlers.
Error handlers are normal Pluggable Views but instead of being registered for routes, they are registered for exceptions that are raised while trying to do something else.
@app.errorhandler(werkzeug.exceptions.BadRequest) def handle_bad_request(e): return 'bad request!' app.register_error_handler(400, lambda e: 'bad request!')
Those two ways are equivalent, but the first one is more clear and leaves you with a function to call on your whim (and in tests). Note that
werkzeug.exceptions.HTTPException subclasses like
BadRequest from the example and their HTTP codes are interchangeable when handed to the registration methods or decorator (
BadRequest.code == 400).
You are however not limited to
HTTPException or HTTP status codes but can register a handler for every exception class you like.
Changed in version 0.11: Errorhandlers are now prioritized by specificity of the exception classes they are registered for instead of the order they are registered in.
Once an exception instance is raised, its class hierarchy is traversed, and searched for in the exception classes for which handlers are registered. The most specific handler is selected.
E.g. if an instance of
ConnectionRefusedError is raised, and a handler is registered for
ConnectionRefusedError, the more specific
ConnectionRefusedError handler is called on the exception instance, and its response is shown to the user.
If the application runs in production mode (which it will do on your server) you might not see any log messages. The reason for that is that Flask by default will just report to the WSGI error stream or stderr (depending on what’s available). Where this ends up is sometimes hard to find. Often it’s in your webserver’s log files.
I can pretty much promise you however that if you only use a logfile for the application errors you will never look at it except for debugging an issue when a user reported it for you. What you probably want instead is a mail the second the exception happened. Then you get an alert and you can do something about it.
Flask uses the Python builtin logging system, and it can actually send you mails for errors which is probably what you want. Here is how you can configure the Flask logger to send you mails for exceptions:
ADMINS = ['[email protected]'] if not app.debug: import logging from logging.handlers import SMTPHandler mail_handler = SMTPHandler('127.0.0.1', '[email protected]', ADMINS, 'YourApplication Failed') mail_handler.setLevel(logging.ERROR) app.logger.addHandler(mail_handler)
So what just happened? We created a new
SMTPHandler that will send mails with the mail server listening on
127.0.0.1 to all the
ADMINS from the address [email protected] with the subject “YourApplication Failed”. If your mail server requires credentials, these can also be provided. For that check out the documentation for the
We also tell the handler to only send errors and more critical messages. Because we certainly don’t want to get a mail for warnings or other useless logs that might happen during request handling.
Before you run that in production, please also look at Controlling the Log Format to put more information into that error mail. That will save you from a lot of frustration.
Even if you get mails, you probably also want to log warnings. It’s a good idea to keep as much information around that might be required to debug a problem. By default as of Flask 0.11, errors are logged to your webserver’s log automatically. Warnings however are not. Please note that Flask itself will not issue any warnings in the core system, so it’s your responsibility to warn in the code if something seems odd.
There are a couple of handlers provided by the logging system out of the box but not all of them are useful for basic error logging. The most interesting are probably the following:
FileHandler- logs messages to a file on the filesystem.
RotatingFileHandler- logs messages to a file on the filesystem and will rotate after a certain number of messages.
NTEventLogHandler- will log to the system event log of a Windows system. If you are deploying on a Windows box, this is what you want to use.
SysLogHandler- sends logs to a UNIX syslog.
Once you picked your log handler, do like you did with the SMTP handler above, just make sure to use a lower setting (I would recommend
if not app.debug: import logging from themodule import TheHandlerYouWant file_handler = TheHandlerYouWant(...) file_handler.setLevel(logging.WARNING) app.logger.addHandler(file_handler)
By default a handler will only write the message string into a file or send you that message as mail. A log record stores more information, and it makes a lot of sense to configure your logger to also contain that information so that you have a better idea of why that error happened, and more importantly, where it did.
A formatter can be instantiated with a format string. Note that tracebacks are appended to the log entry automatically. You don’t have to do that in the log formatter format string.
Here are some example setups:
from logging import Formatter mail_handler.setFormatter(Formatter(''' Message type: %(levelname)s Location: %(pathname)s:%(lineno)d Module: %(module)s Function: %(funcName)s Time: %(asctime)s Message: %(message)s '''))
from logging import Formatter file_handler.setFormatter(Formatter( '%(asctime)s %(levelname)s: %(message)s ' '[in %(pathname)s:%(lineno)d]' ))
Here is a list of useful formatting variables for the format string. Note that this list is not complete, consult the official documentation of the
logging package for a full list.
| || |
Text logging level for the message (
| || |
Full pathname of the source file where the logging call was issued (if available).
| || |
Filename portion of pathname.
| || |
Module (name portion of filename).
| || |
Name of function containing the logging call.
| || |
Source line number where the logging call was issued (if available).
| || |
Human-readable time when the
| || |
The logged message, computed as
If you want to further customize the formatting, you can subclass the formatter. The formatter has three interesting methods:
handles the actual formatting. It is passed a
LogRecord object and has to return the formatted string.
asctime formatting. If you want a different time format you can override this method.
called for exception formatting. It is passed an
exc_info tuple and has to return a string. The default is usually fine, you don’t have to override it.
For more information, head over to the official documentation.
So far we only configured the logger your application created itself. Other libraries might log themselves as well. For example, SQLAlchemy uses logging heavily in its core. While there is a method to configure all loggers at once in the
logging package, I would not recommend using it. There might be a situation in which you want to have multiple separate applications running side by side in the same Python interpreter and then it becomes impossible to have different logging setups for those.
Instead, I would recommend figuring out which loggers you are interested in, getting the loggers with the
getLogger() function and iterating over them to attach handlers:
from logging import getLogger loggers = [app.logger, getLogger('sqlalchemy'), getLogger('otherlibrary')] for logger in loggers: logger.addHandler(mail_handler) logger.addHandler(file_handler)
© 2007–2020 Pallets
Licensed under the BSD 3-clause License.