Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

394 lines · 15.5 KiB

Last changed by

Migrate various docs links to https (#2180)Jeff Widmanbefore adoptionbb0e755

History of this file

Take it

1.. _application-errors:23Application Errors4==================56.. versionadded:: 0.378Applications fail, servers fail.  Sooner or later you will see an exception9in production.  Even if your code is 100% correct, you will still see10exceptions from time to time.  Why?  Because everything else involved will11fail.  Here are some situations where perfectly fine code can lead to server12errors:1314-   the client terminated the request early and the application was still15    reading from the incoming data16-   the database server was overloaded and could not handle the query17-   a filesystem is full18-   a harddrive crashed19-   a backend server overloaded20-   a programming error in a library you are using21-   network connection of the server to another system failed2223And that's just a small sample of issues you could be facing.  So how do we24deal with that sort of problem?  By default if your application runs in25production mode, Flask will display a very simple page for you and log the26exception to the :attr:`~flask.Flask.logger`.2728But there is more you can do, and we will cover some better setups to deal29with errors.3031Error Logging Tools32-------------------3334Sending error mails, even if just for critical ones, can become35overwhelming if enough users are hitting the error and log files are36typically never looked at. This is why we recommend using `Sentry37<https://www.getsentry.com/>`_ for dealing with application errors.  It's38available as an Open Source project `on GitHub39<https://github.com/getsentry/sentry>`__ and is also available as a `hosted version40<https://getsentry.com/signup/>`_ which you can try for free. Sentry41aggregates duplicate errors, captures the full stack trace and local42variables for debugging, and sends you mails based on new errors or43frequency thresholds.4445To use Sentry you need to install the `raven` client::4647    $ pip install raven4849And then add this to your Flask app::5051    from raven.contrib.flask import Sentry52    sentry = Sentry(app, dsn='YOUR_DSN_HERE')5354Or if you are using factories you can also init it later::5556    from raven.contrib.flask import Sentry57    sentry = Sentry(dsn='YOUR_DSN_HERE')5859    def create_app():60        app = Flask(__name__)61        sentry.init_app(app)62        ...63        return app6465The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get66from your Sentry installation.6768Afterwards failures are automatically reported to Sentry and from there69you can receive error notifications.7071.. _error-handlers:7273Error handlers74--------------7576You might want to show custom error pages to the user when an error occurs.77This can be done by registering error handlers.7879Error handlers are normal :ref:`views` but instead of being registered for80routes, they are registered for exceptions that are raised while trying to81do something else.8283Registering84```````````8586Register error handlers using :meth:`~flask.Flask.errorhandler` or87:meth:`~flask.Flask.register_error_handler`::8889    @app.errorhandler(werkzeug.exceptions.BadRequest)90    def handle_bad_request(e):91        return 'bad request!'9293    app.register_error_handler(400, lambda e: 'bad request!')9495Those two ways are equivalent, but the first one is more clear and leaves96you with a function to call on your whim (and in tests).  Note that97:exc:`werkzeug.exceptions.HTTPException` subclasses like98:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes99are interchangeable when handed to the registration methods or decorator100(``BadRequest.code == 400``).101102You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103or HTTP status codes but can register a handler for every exception class you104like.105106.. versionchanged:: 0.11107108   Errorhandlers are now prioritized by specificity of the exception classes109   they are registered for instead of the order they are registered in.110111Handling112````````113114Once an exception instance is raised, its class hierarchy is traversed,115and searched for in the exception classes for which handlers are registered.116The most specific handler is selected.117118E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler119is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,120the more specific :exc:`ConnectionRefusedError` handler is called on the121exception instance, and its response is shown to the user.122123Error Mails124-----------125126If the application runs in production mode (which it will do on your127server) you might not see any log messages.  The reason for that is that128Flask by default will just report to the WSGI error stream or stderr129(depending on what's available).  Where this ends up is sometimes hard to130find.  Often it's in your webserver's log files.131132I can pretty much promise you however that if you only use a logfile for133the application errors you will never look at it except for debugging an134issue when a user reported it for you.  What you probably want instead is135a mail the second the exception happened.  Then you get an alert and you136can do something about it.137138Flask uses the Python builtin logging system, and it can actually send139you mails for errors which is probably what you want.  Here is how you can140configure the Flask logger to send you mails for exceptions::141142    ADMINS = ['yourname@example.com']143    if not app.debug:144        import logging145        from logging.handlers import SMTPHandler146        mail_handler = SMTPHandler('127.0.0.1',147                                   'server-error@example.com',148                                   ADMINS, 'YourApplication Failed')149        mail_handler.setLevel(logging.ERROR)150        app.logger.addHandler(mail_handler)151152So what just happened?  We created a new153:class:`~logging.handlers.SMTPHandler` that will send mails with the mail154server listening on ``127.0.0.1`` to all the `ADMINS` from the address155*server-error@example.com* with the subject "YourApplication Failed".  If156your mail server requires credentials, these can also be provided.  For157that check out the documentation for the158:class:`~logging.handlers.SMTPHandler`.159160We also tell the handler to only send errors and more critical messages.161Because we certainly don't want to get a mail for warnings or other162useless logs that might happen during request handling.163164Before you run that in production, please also look at :ref:`logformat` to165put more information into that error mail.  That will save you from a lot166of frustration.167168169Logging to a File170-----------------171172Even if you get mails, you probably also want to log warnings.  It's a173good idea to keep as much information around that might be required to174debug a problem.  By default as of Flask 0.11, errors are logged to your175webserver's log automatically.  Warnings however are not.  Please note176that Flask itself will not issue any warnings in the core system, so it's177your responsibility to warn in the code if something seems odd.178179There are a couple of handlers provided by the logging system out of the180box but not all of them are useful for basic error logging.  The most181interesting are probably the following:182183-   :class:`~logging.FileHandler` - logs messages to a file on the184    filesystem.185-   :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file186    on the filesystem and will rotate after a certain number of messages.187-   :class:`~logging.handlers.NTEventLogHandler` - will log to the system188    event log of a Windows system.  If you are deploying on a Windows box,189    this is what you want to use.190-   :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX191    syslog.192193Once you picked your log handler, do like you did with the SMTP handler194above, just make sure to use a lower setting (I would recommend195`WARNING`)::196197    if not app.debug:198        import logging199        from themodule import TheHandlerYouWant200        file_handler = TheHandlerYouWant(...)201        file_handler.setLevel(logging.WARNING)202        app.logger.addHandler(file_handler)203204.. _logformat:205206Controlling the Log Format207--------------------------208209By default a handler will only write the message string into a file or210send you that message as mail.  A log record stores more information,211and it makes a lot of sense to configure your logger to also contain that212information so that you have a better idea of why that error happened, and213more importantly, where it did.214215A formatter can be instantiated with a format string.  Note that216tracebacks are appended to the log entry automatically.  You don't have to217do that in the log formatter format string.218219Here are some example setups:220221Email222`````223224::225226    from logging import Formatter227    mail_handler.setFormatter(Formatter('''228    Message type:       %(levelname)s229    Location:           %(pathname)s:%(lineno)d230    Module:             %(module)s231    Function:           %(funcName)s232    Time:               %(asctime)s233234    Message:235236    %(message)s237    '''))238239File logging240````````````241242::243244    from logging import Formatter245    file_handler.setFormatter(Formatter(246        '%(asctime)s %(levelname)s: %(message)s '247        '[in %(pathname)s:%(lineno)d]'248    ))249250251Complex Log Formatting252``````````````````````253254Here is a list of useful formatting variables for the format string.  Note255that this list is not complete, consult the official documentation of the256:mod:`logging` package for a full list.257258.. tabularcolumns:: |p{3cm}|p{12cm}|259260+------------------+----------------------------------------------------+261| Format           | Description                                        |262+==================+====================================================+263| ``%(levelname)s``| Text logging level for the message                 |264|                  | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,           |265|                  | ``'ERROR'``, ``'CRITICAL'``).                      |266+------------------+----------------------------------------------------+267| ``%(pathname)s`` | Full pathname of the source file where the         |268|                  | logging call was issued (if available).            |269+------------------+----------------------------------------------------+270| ``%(filename)s`` | Filename portion of pathname.                      |271+------------------+----------------------------------------------------+272| ``%(module)s``   | Module (name portion of filename).                 |273+------------------+----------------------------------------------------+274| ``%(funcName)s`` | Name of function containing the logging call.      |275+------------------+----------------------------------------------------+276| ``%(lineno)d``   | Source line number where the logging call was      |277|                  | issued (if available).                             |278+------------------+----------------------------------------------------+279| ``%(asctime)s``  | Human-readable time when the                       |280|                  | :class:`~logging.LogRecord` was created.           |281|                  | By default this is of the form                     |282|                  | ``"2003-07-08 16:49:45,896"`` (the numbers after   |283|                  | the comma are millisecond portion of the time).    |284|                  | This can be changed by subclassing the formatter   |285|                  | and overriding the                                 |286|                  | :meth:`~logging.Formatter.formatTime` method.      |287+------------------+----------------------------------------------------+288| ``%(message)s``  | The logged message, computed as ``msg % args``     |289+------------------+----------------------------------------------------+290291If you want to further customize the formatting, you can subclass the292formatter.  The formatter has three interesting methods:293294:meth:`~logging.Formatter.format`:295    handles the actual formatting.  It is passed a296    :class:`~logging.LogRecord` object and has to return the formatted297    string.298:meth:`~logging.Formatter.formatTime`:299    called for `asctime` formatting.  If you want a different time format300    you can override this method.301:meth:`~logging.Formatter.formatException`302    called for exception formatting.  It is passed an :attr:`~sys.exc_info`303    tuple and has to return a string.  The default is usually fine, you304    don't have to override it.305306For more information, head over to the official documentation.307308309Other Libraries310---------------311312So far we only configured the logger your application created itself.313Other libraries might log themselves as well.  For example, SQLAlchemy uses314logging heavily in its core.  While there is a method to configure all315loggers at once in the :mod:`logging` package, I would not recommend using316it.  There might be a situation in which you want to have multiple317separate applications running side by side in the same Python interpreter318and then it becomes impossible to have different logging setups for those.319320Instead, I would recommend figuring out which loggers you are interested321in, getting the loggers with the :func:`~logging.getLogger` function and322iterating over them to attach handlers::323324    from logging import getLogger325    loggers = [app.logger, getLogger('sqlalchemy'),326               getLogger('otherlibrary')]327    for logger in loggers:328        logger.addHandler(mail_handler)329        logger.addHandler(file_handler)330331332Debugging Application Errors333============================334335For production applications, configure your application with logging and336notifications as described in :ref:`application-errors`.  This section provides337pointers when debugging deployment configuration and digging deeper with a338full-featured Python debugger.339340341When in Doubt, Run Manually342---------------------------343344Having problems getting your application configured for production?  If you345have shell access to your host, verify that you can run your application346manually from the shell in the deployment environment.  Be sure to run under347the same user account as the configured deployment to troubleshoot permission348issues.  You can use Flask's builtin development server with `debug=True` on349your production host, which is helpful in catching configuration issues, but350**be sure to do this temporarily in a controlled environment.** Do not run in351production with `debug=True`.352353354.. _working-with-debuggers:355356Working with Debuggers357----------------------358359To dig deeper, possibly to trace code execution, Flask provides a debugger out360of the box (see :ref:`debug-mode`).  If you would like to use another Python361debugger, note that debuggers interfere with each other.  You have to set some362options in order to use your favorite debugger:363364* ``debug``        - whether to enable debug mode and catch exceptions365* ``use_debugger`` - whether to use the internal Flask debugger366* ``use_reloader`` - whether to reload and fork the process on exception367368``debug`` must be True (i.e., exceptions must be caught) in order for the other369two options to have any value.370371If you're using Aptana/Eclipse for debugging you'll need to set both372``use_debugger`` and ``use_reloader`` to False.373374A possible useful pattern for configuration is to set the following in your375config.yaml (change the block as appropriate for your application, of course)::376377   FLASK:378       DEBUG: True379       DEBUG_WITH_APTANA: True380381Then in your application's entry-point (main.py), you could have something like::382383   if __name__ == "__main__":384       # To allow aptana to receive errors, set use_debugger=False385       app = create_app(config="config.yaml")386387       if app.debug: use_debugger = True388       try:389           # Disable Flask's debugger if external debugger is requested390           use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))391       except:392           pass393       app.run(use_debugger=use_debugger, debug=app.debug,394               use_reloader=use_debugger, host='0.0.0.0')