Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

353 lines · 14.1 KiB

Last changed by

minor revision of documentation.bagrattebefore adoption9a80fe6

History of this file

Take it

The walk stopped after 200 commits: lines older than 0a7cc2b point at it.

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 1–2why, one step back
1.. _application-errors:
2

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

lines 3–4why, one step back
3Application Errors
4==================

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 5–29why, one step back
5
6.. 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

lines 30–58why, one step back
30
31.. _error-handlers:3233Error handlers34--------------3536You might want to show custom error pages to the user when an error occurs.37This can be done by registering error handlers.3839Error handlers are normal :ref:`views` but instead of being registered for40routes they are registered for exceptions that are rised while trying to41do something else.4243Registering44```````````4546Register error handlers using :meth:`~flask.Flask.errorhandler` or47:meth:`~flask.Flask.register_error_handler`::4849 @app.errorhandler(werkzeug.exceptions.BadRequest)50 def handle_bad_request(e):51 return 'bad request!'52 53 app.register_error_handler(400, lambda e: 'bad request!')5455Those two ways are equivalent, but the first one is more clear and leaves56you with a function to call on your whim (and in tests). Note that57:exc:`werkzeug.exceptions.HTTPException` subclasses like58:exc:`~werkzeug.exceptions.BadRequest` from the example and their HTTP codes

Merge pull request #1721 from pra85/patch-1David Lordbefore adoptionf63cd72

line 59why, one step back
59are interchangeable when handed to the registration methods or decorator

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

lines 60–61why, one step back
60(``BadRequest.code == 400``).
61

minor revision of documentation.bagrattebefore adoption9a80fe6

lines 62–64why, one step back
62You are however not limited to :exc:`~werkzeug.exceptions.HTTPException`
63or HTTP status codes but can register a handler for every exception class you64like.

Errorhandlers were NOT *added* in 1.0Markus Unterwaditzerbefore adoption73d89cc

lines 65–67why, one step back
65
66.. versionchanged:: 1.067

minor revision of documentation.bagrattebefore adoption9a80fe6

lines 68–69why, one step back
68 Errorhandlers are now prioritized by specificity of the exception classes
69 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 70–77why, one step back
70
71Handling72````````7374Once an exception instance is raised, its class hierarchy is traversed,75and searched for in the exception classes for which handlers are registered.76The most specific handler is selected.77

minor revision of documentation.bagrattebefore adoption9a80fe6

line 78why, one step back
78E.g. if an instance of :exc:`ConnectionRefusedError` is raised, and a handler

Merge pull request #1429 from flying-sheep/errorhandler-rework-docsMarkus Unterwaditzerbefore adoption06f2be3

lines 79–81why, one step back
79is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,
80the more specific :exc:`ConnectionRefusedError` handler is called on the81exception instance, and its response is shown to the user.

Fix typoMarkus Unterwaditzerbefore adoption0a7cc2b

lines 82–353why, one step back
82
83Error Mails84-----------8586If the application runs in production mode (which it will do on your87server) you might not see any log messages. The reason for that is that88Flask by default will just report to the WSGI error stream or stderr89(depending on what's available). Where this ends up is sometimes hard to90find. Often it's in your webserver's log files.9192I can pretty much promise you however that if you only use a logfile for93the application errors you will never look at it except for debugging an94issue when a user reported it for you. What you probably want instead is95a mail the second the exception happened. Then you get an alert and you96can do something about it.9798Flask uses the Python builtin logging system, and it can actually send99you mails for errors which is probably what you want. Here is how you can100configure the Flask logger to send you mails for exceptions::101102 ADMINS = ['yourname@example.com']103 if not app.debug:104 import logging105 from logging.handlers import SMTPHandler106 mail_handler = SMTPHandler('127.0.0.1',107 'server-error@example.com',108 ADMINS, 'YourApplication Failed')109 mail_handler.setLevel(logging.ERROR)110 app.logger.addHandler(mail_handler)111112So what just happened? We created a new113:class:`~logging.handlers.SMTPHandler` that will send mails with the mail114server listening on ``127.0.0.1`` to all the `ADMINS` from the address115*server-error@example.com* with the subject "YourApplication Failed". If116your mail server requires credentials, these can also be provided. For117that check out the documentation for the118:class:`~logging.handlers.SMTPHandler`.119120We also tell the handler to only send errors and more critical messages.121Because we certainly don't want to get a mail for warnings or other122useless logs that might happen during request handling.123124Before you run that in production, please also look at :ref:`logformat` to125put more information into that error mail. That will save you from a lot126of frustration.127128129Logging to a File130-----------------131132Even if you get mails, you probably also want to log warnings. It's a133good idea to keep as much information around that might be required to134debug a problem. By default as of Flask 1.0, errors are logged to your135webserver's log automatically. Warnings however are not. Please note136that Flask itself will not issue any warnings in the core system, so it's137your responsibility to warn in the code if something seems odd.138139There are a couple of handlers provided by the logging system out of the140box but not all of them are useful for basic error logging. The most141interesting are probably the following:142143- :class:`~logging.FileHandler` - logs messages to a file on the144 filesystem.145- :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file146 on the filesystem and will rotate after a certain number of messages.147- :class:`~logging.handlers.NTEventLogHandler` - will log to the system148 event log of a Windows system. If you are deploying on a Windows box,149 this is what you want to use.150- :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX151 syslog.152153Once you picked your log handler, do like you did with the SMTP handler154above, just make sure to use a lower setting (I would recommend155`WARNING`)::156157 if not app.debug:158 import logging159 from themodule import TheHandlerYouWant160 file_handler = TheHandlerYouWant(...)161 file_handler.setLevel(logging.WARNING)162 app.logger.addHandler(file_handler)163164.. _logformat:165166Controlling the Log Format167--------------------------168169By default a handler will only write the message string into a file or170send you that message as mail. A log record stores more information,171and it makes a lot of sense to configure your logger to also contain that172information so that you have a better idea of why that error happened, and173more importantly, where it did.174175A formatter can be instantiated with a format string. Note that176tracebacks are appended to the log entry automatically. You don't have to177do that in the log formatter format string.178179Here some example setups:180181Email182`````183184::185186 from logging import Formatter187 mail_handler.setFormatter(Formatter('''188 Message type: %(levelname)s189 Location: %(pathname)s:%(lineno)d190 Module: %(module)s191 Function: %(funcName)s192 Time: %(asctime)s193194 Message:195196 %(message)s197 '''))198199File logging200````````````201202::203204 from logging import Formatter205 file_handler.setFormatter(Formatter(206 '%(asctime)s %(levelname)s: %(message)s '207 '[in %(pathname)s:%(lineno)d]'208 ))209210211Complex Log Formatting212``````````````````````213214Here is a list of useful formatting variables for the format string. Note215that this list is not complete, consult the official documentation of the216:mod:`logging` package for a full list.217218.. tabularcolumns:: |p{3cm}|p{12cm}|219220+------------------+----------------------------------------------------+221| Format | Description |222+==================+====================================================+223| ``%(levelname)s``| Text logging level for the message |224| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |225| | ``'ERROR'``, ``'CRITICAL'``). |226+------------------+----------------------------------------------------+227| ``%(pathname)s`` | Full pathname of the source file where the |228| | logging call was issued (if available). |229+------------------+----------------------------------------------------+230| ``%(filename)s`` | Filename portion of pathname. |231+------------------+----------------------------------------------------+232| ``%(module)s`` | Module (name portion of filename). |233+------------------+----------------------------------------------------+234| ``%(funcName)s`` | Name of function containing the logging call. |235+------------------+----------------------------------------------------+236| ``%(lineno)d`` | Source line number where the logging call was |237| | issued (if available). |238+------------------+----------------------------------------------------+239| ``%(asctime)s`` | Human-readable time when the LogRecord` was |240| | created. By default this is of the form |241| | ``"2003-07-08 16:49:45,896"`` (the numbers after |242| | the comma are millisecond portion of the time). |243| | This can be changed by subclassing the formatter |244| | and overriding the |245| | :meth:`~logging.Formatter.formatTime` method. |246+------------------+----------------------------------------------------+247| ``%(message)s`` | The logged message, computed as ``msg % args`` |248+------------------+----------------------------------------------------+249250If you want to further customize the formatting, you can subclass the251formatter. The formatter has three interesting methods:252253:meth:`~logging.Formatter.format`:254 handles the actual formatting. It is passed a255 :class:`~logging.LogRecord` object and has to return the formatted256 string.257:meth:`~logging.Formatter.formatTime`:258 called for `asctime` formatting. If you want a different time format259 you can override this method.260:meth:`~logging.Formatter.formatException`261 called for exception formatting. It is passed an :attr:`~sys.exc_info`262 tuple and has to return a string. The default is usually fine, you263 don't have to override it.264265For more information, head over to the official documentation.266267268Other Libraries269---------------270271So far we only configured the logger your application created itself.272Other libraries might log themselves as well. For example, SQLAlchemy uses273logging heavily in its core. While there is a method to configure all274loggers at once in the :mod:`logging` package, I would not recommend using275it. There might be a situation in which you want to have multiple276separate applications running side by side in the same Python interpreter277and then it becomes impossible to have different logging setups for those.278279Instead, I would recommend figuring out which loggers you are interested280in, getting the loggers with the :func:`~logging.getLogger` function and281iterating over them to attach handlers::282283 from logging import getLogger284 loggers = [app.logger, getLogger('sqlalchemy'),285 getLogger('otherlibrary')]286 for logger in loggers:287 logger.addHandler(mail_handler)288 logger.addHandler(file_handler)289290291Debugging Application Errors292============================293294For production applications, configure your application with logging and295notifications as described in :ref:`application-errors`. This section provides296pointers when debugging deployment configuration and digging deeper with a297full-featured Python debugger.298299300When in Doubt, Run Manually301---------------------------302303Having problems getting your application configured for production? If you304have shell access to your host, verify that you can run your application305manually from the shell in the deployment environment. Be sure to run under306the same user account as the configured deployment to troubleshoot permission307issues. You can use Flask's builtin development server with `debug=True` on308your production host, which is helpful in catching configuration issues, but309**be sure to do this temporarily in a controlled environment.** Do not run in310production with `debug=True`.311312313.. _working-with-debuggers:314315Working with Debuggers316----------------------317318To dig deeper, possibly to trace code execution, Flask provides a debugger out319of the box (see :ref:`debug-mode`). If you would like to use another Python320debugger, note that debuggers interfere with each other. You have to set some321options in order to use your favorite debugger:322323* ``debug`` - whether to enable debug mode and catch exceptions324* ``use_debugger`` - whether to use the internal Flask debugger325* ``use_reloader`` - whether to reload and fork the process on exception326327``debug`` must be True (i.e., exceptions must be caught) in order for the other328two options to have any value.329330If you're using Aptana/Eclipse for debugging you'll need to set both331``use_debugger`` and ``use_reloader`` to False.332333A possible useful pattern for configuration is to set the following in your334config.yaml (change the block as appropriate for your application, of course)::335336 FLASK:337 DEBUG: True338 DEBUG_WITH_APTANA: True339340Then in your application's entry-point (main.py), you could have something like::341342 if __name__ == "__main__":343 # To allow aptana to receive errors, set use_debugger=False344 app = create_app(config="config.yaml")345346 if app.debug: use_debugger = True347 try:348 # Disable Flask's debugger if external debugger is requested349 use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))350 except:351 pass352 app.run(use_debugger=use_debugger, debug=app.debug,353 use_reloader=use_debugger, host='0.0.0.0')