errorhandling.rst
This file
Path
docs/errorhandling.rst
393 lines · 15.4 KiB
Last changed by
Merge pull request #1892 from avborhanian/patch-1Markus Unterwaditzerbefore adoption6a3a209
History of this fileTake it
The walk stopped after 200 commits: lines older than 86e8267 point at it.
Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 1–2why, one step back1.. _application-errors:2Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 3–4why, one step back3Application Errors4==================Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 5–29why, one step back56.. 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.Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
line 30why, one step back30Merge pull request #1823 from pallets/feature/sentry-docsArmin Ronacherbefore adoptione83d608
lines 31–38why, one step back31Error 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<http://www.getsentry.com/>`_ for dealing with application errors. It's38available as an Open Source project `on GitHubMerge pull request #1892 from avborhanian/patch-1Markus Unterwaditzerbefore adoption6a3a209
line 39why, one step back39<https://github.com/getsentry/sentry>`__ and is also available as a `hosted versionMerge pull request #1823 from pallets/feature/sentry-docsArmin Ronacherbefore adoptione83d608
lines 40–70why, one step back40<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')5354Of 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.70Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 71–98why, one step back71.. _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 rised 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!'92 93 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 codesMerge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72
line 99why, one step back99are interchangeable when handed to the registration methods or decoratorMerge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 100–101why, one step back100(``BadRequest.code == 400``).101minor revision of documentation.bagrattebefore adoption9a80fe6
lines 102–104why, one step back102You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`103or HTTP status codes but can register a handler for every exception class you104like.Errorhandlers were NOT *added* in 1.0Markus Unterwaditzerbefore adoption73d89cc
line 105why, one step back105s/1.0/0.11/ in versionadded/versionchanged markersThiefMasterbefore adoptionc5900a1
line 106why, one step back106.. versionchanged:: 0.11Errorhandlers were NOT *added* in 1.0Markus Unterwaditzerbefore adoption73d89cc
line 107why, one step back107minor revision of documentation.bagrattebefore adoption9a80fe6
lines 108–109why, one step back108 Errorhandlers are now prioritized by specificity of the exception classes109 they are registered for instead of the order they are registered in.Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 110–117why, one step back110111Handling112````````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.117minor revision of documentation.bagrattebefore adoption9a80fe6
line 118why, one step back118E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handlerMerge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3
lines 119–121why, one step back119is 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.Merge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 122–173why, one step back122123Error 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 to1.0 -> 0.11 in the docsArmin Ronacherbefore adoptionf9ea3fe
line 174why, one step back174debug a problem. By default as of Flask 0.11, errors are logged to yourMerge pull request #1378 from cbron/masterKeyan Pishdadianbefore adoption86e8267
lines 175–393why, one step back175webserver'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 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 LogRecord` was |280| | created. By default this is of the form |281| | ``"2003-07-08 16:49:45,896"`` (the numbers after |282| | the comma are millisecond portion of the time). |283| | This can be changed by subclassing the formatter |284| | and overriding the |285| | :meth:`~logging.Formatter.formatTime` method. |286+------------------+----------------------------------------------------+287| ``%(message)s`` | The logged message, computed as ``msg % args`` |288+------------------+----------------------------------------------------+289290If you want to further customize the formatting, you can subclass the291formatter. The formatter has three interesting methods:292293:meth:`~logging.Formatter.format`:294 handles the actual formatting. It is passed a295 :class:`~logging.LogRecord` object and has to return the formatted296 string.297:meth:`~logging.Formatter.formatTime`:298 called for `asctime` formatting. If you want a different time format299 you can override this method.300:meth:`~logging.Formatter.formatException`301 called for exception formatting. It is passed an :attr:`~sys.exc_info`302 tuple and has to return a string. The default is usually fine, you303 don't have to override it.304305For more information, head over to the official documentation.306307308Other Libraries309---------------310311So far we only configured the logger your application created itself.312Other libraries might log themselves as well. For example, SQLAlchemy uses313logging heavily in its core. While there is a method to configure all314loggers at once in the :mod:`logging` package, I would not recommend using315it. There might be a situation in which you want to have multiple316separate applications running side by side in the same Python interpreter317and then it becomes impossible to have different logging setups for those.318319Instead, I would recommend figuring out which loggers you are interested320in, getting the loggers with the :func:`~logging.getLogger` function and321iterating over them to attach handlers::322323 from logging import getLogger324 loggers = [app.logger, getLogger('sqlalchemy'),325 getLogger('otherlibrary')]326 for logger in loggers:327 logger.addHandler(mail_handler)328 logger.addHandler(file_handler)329330331Debugging Application Errors332============================333334For production applications, configure your application with logging and335notifications as described in :ref:`application-errors`. This section provides336pointers when debugging deployment configuration and digging deeper with a337full-featured Python debugger.338339340When in Doubt, Run Manually341---------------------------342343Having problems getting your application configured for production? If you344have shell access to your host, verify that you can run your application345manually from the shell in the deployment environment. Be sure to run under346the same user account as the configured deployment to troubleshoot permission347issues. You can use Flask's builtin development server with `debug=True` on348your production host, which is helpful in catching configuration issues, but349**be sure to do this temporarily in a controlled environment.** Do not run in350production with `debug=True`.351352353.. _working-with-debuggers:354355Working with Debuggers356----------------------357358To dig deeper, possibly to trace code execution, Flask provides a debugger out359of the box (see :ref:`debug-mode`). If you would like to use another Python360debugger, note that debuggers interfere with each other. You have to set some361options in order to use your favorite debugger:362363* ``debug`` - whether to enable debug mode and catch exceptions364* ``use_debugger`` - whether to use the internal Flask debugger365* ``use_reloader`` - whether to reload and fork the process on exception366367``debug`` must be True (i.e., exceptions must be caught) in order for the other368two options to have any value.369370If you're using Aptana/Eclipse for debugging you'll need to set both371``use_debugger`` and ``use_reloader`` to False.372373A possible useful pattern for configuration is to set the following in your374config.yaml (change the block as appropriate for your application, of course)::375376 FLASK:377 DEBUG: True378 DEBUG_WITH_APTANA: True379380Then in your application's entry-point (main.py), you could have something like::381382 if __name__ == "__main__":383 # To allow aptana to receive errors, set use_debugger=False384 app = create_app(config="config.yaml")385386 if app.debug: use_debugger = True387 try:388 # Disable Flask's debugger if external debugger is requested389 use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))390 except:391 pass392 app.run(use_debugger=use_debugger, debug=app.debug,393 use_reloader=use_debugger, host='0.0.0.0')