Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

352 lines · 14.0 KiB

Last changed by

Errorhandlers were NOT *added* in 1.0Markus Unterwaditzerbefore adoption73d89cc

History of this file

Take it

The walk stopped after 200 commits: lines older than 5693b9d point at it.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

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==================

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 5–10why, 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 will

Merge pull request #1150 from kylepjohnson/masterMarkus Unterwaditzerbefore adoption01450ef

line 11why, one step back
11fail. Here are some situations where perfectly fine code can lead to server

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 12–14why, one step back
12errors:
1314- the client terminated the request early and the application was still

Merge pull request #1150 from kylepjohnson/masterMarkus Unterwaditzerbefore adoption01450ef

lines 15–16why, one step back
15 reading from the incoming data
16- the database server was overloaded and could not handle the query

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 17–20why, one step back
17- a filesystem is full
18- a harddrive crashed19- a backend server overloaded20- a programming error in a library you are using

Merge pull request #1150 from kylepjohnson/masterMarkus Unterwaditzerbefore adoption01450ef

line 21why, one step back
21- network connection of the server to another system failed

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 22–29why, one step back
22
23And 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–63why, 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 codes59are interchangable when handed to the registration methods or decorator60(``BadRequest.code == 400``).6162You are however not limited to a :exc:`~werkzeug.exceptions.HTTPException`63or its code but can register a handler for every exception class you like.

Errorhandlers were NOT *added* in 1.0Markus Unterwaditzerbefore adoption73d89cc

lines 64–68why, one step back
64
65.. versionchanged:: 1.06667 Errorhandlers are now prioritized by specifity instead of the order they're68 registered in.

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

lines 69–80why, one step back
69
70Handling71````````7273Once an exception instance is raised, its class hierarchy is traversed,74and searched for in the exception classes for which handlers are registered.75The most specific handler is selected.7677E.g. if a instance of :exc:`ConnectionRefusedError` is raised, and a handler78is registered for :exc:`ConnectionError` and :exc:`ConnectionRefusedError`,79the more specific :exc:`ConnectionRefusedError` handler is called on the80exception instance, and its response is shown to the user.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 81–85why, one step back
81
82Error Mails83-----------8485If the application runs in production mode (which it will do on your

Updated the logging documentation for recent changes.Armin Ronacherbefore adoption7c16054

lines 86–89why, one step back
86server) you might not see any log messages. The reason for that is that
87Flask by default will just report to the WSGI error stream or stderr88(depending on what's available). Where this ends up is sometimes hard to89find. Often it's in your webserver's log files.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

line 90why, one step back
90

Updated the logging documentation for recent changes.Armin Ronacherbefore adoption7c16054

lines 91–95why, one step back
91I can pretty much promise you however that if you only use a logfile for
92the application errors you will never look at it except for debugging an93issue when a user reported it for you. What you probably want instead is94a mail the second the exception happened. Then you get an alert and you95can do something about it.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 96–132why, one step back
96
97Flask uses the Python builtin logging system, and it can actually send98you mails for errors which is probably what you want. Here is how you can99configure the Flask logger to send you mails for exceptions::100101 ADMINS = ['yourname@example.com']102 if not app.debug:103 import logging104 from logging.handlers import SMTPHandler105 mail_handler = SMTPHandler('127.0.0.1',106 'server-error@example.com',107 ADMINS, 'YourApplication Failed')108 mail_handler.setLevel(logging.ERROR)109 app.logger.addHandler(mail_handler)110111So what just happened? We created a new112:class:`~logging.handlers.SMTPHandler` that will send mails with the mail113server listening on ``127.0.0.1`` to all the `ADMINS` from the address114*server-error@example.com* with the subject "YourApplication Failed". If115your mail server requires credentials, these can also be provided. For116that check out the documentation for the117:class:`~logging.handlers.SMTPHandler`.118119We also tell the handler to only send errors and more critical messages.120Because we certainly don't want to get a mail for warnings or other121useless logs that might happen during request handling.122123Before you run that in production, please also look at :ref:`logformat` to124put more information into that error mail. That will save you from a lot125of frustration.126127128Logging to a File129-----------------130131Even if you get mails, you probably also want to log warnings. It's a132good idea to keep as much information around that might be required to

Updated the logging documentation for recent changes.Armin Ronacherbefore adoption7c16054

lines 133–136why, one step back
133debug a problem. By default as of Flask 1.0, errors are logged to your
134webserver's log automatically. Warnings however are not. Please note135that Flask itself will not issue any warnings in the core system, so it's136your responsibility to warn in the code if something seems odd.

Merge branch 'pr/839'Armin Ronacherbefore adoption5693b9d

lines 137–352why, one step back
137
138There are a couple of handlers provided by the logging system out of the139box but not all of them are useful for basic error logging. The most140interesting are probably the following:141142- :class:`~logging.FileHandler` - logs messages to a file on the143 filesystem.144- :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file145 on the filesystem and will rotate after a certain number of messages.146- :class:`~logging.handlers.NTEventLogHandler` - will log to the system147 event log of a Windows system. If you are deploying on a Windows box,148 this is what you want to use.149- :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX150 syslog.151152Once you picked your log handler, do like you did with the SMTP handler153above, just make sure to use a lower setting (I would recommend154`WARNING`)::155156 if not app.debug:157 import logging158 from themodule import TheHandlerYouWant159 file_handler = TheHandlerYouWant(...)160 file_handler.setLevel(logging.WARNING)161 app.logger.addHandler(file_handler)162163.. _logformat:164165Controlling the Log Format166--------------------------167168By default a handler will only write the message string into a file or169send you that message as mail. A log record stores more information,170and it makes a lot of sense to configure your logger to also contain that171information so that you have a better idea of why that error happened, and172more importantly, where it did.173174A formatter can be instantiated with a format string. Note that175tracebacks are appended to the log entry automatically. You don't have to176do that in the log formatter format string.177178Here some example setups:179180Email181`````182183::184185 from logging import Formatter186 mail_handler.setFormatter(Formatter('''187 Message type: %(levelname)s188 Location: %(pathname)s:%(lineno)d189 Module: %(module)s190 Function: %(funcName)s191 Time: %(asctime)s192193 Message:194195 %(message)s196 '''))197198File logging199````````````200201::202203 from logging import Formatter204 file_handler.setFormatter(Formatter(205 '%(asctime)s %(levelname)s: %(message)s '206 '[in %(pathname)s:%(lineno)d]'207 ))208209210Complex Log Formatting211``````````````````````212213Here is a list of useful formatting variables for the format string. Note214that this list is not complete, consult the official documentation of the215:mod:`logging` package for a full list.216217.. tabularcolumns:: |p{3cm}|p{12cm}|218219+------------------+----------------------------------------------------+220| Format | Description |221+==================+====================================================+222| ``%(levelname)s``| Text logging level for the message |223| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |224| | ``'ERROR'``, ``'CRITICAL'``). |225+------------------+----------------------------------------------------+226| ``%(pathname)s`` | Full pathname of the source file where the |227| | logging call was issued (if available). |228+------------------+----------------------------------------------------+229| ``%(filename)s`` | Filename portion of pathname. |230+------------------+----------------------------------------------------+231| ``%(module)s`` | Module (name portion of filename). |232+------------------+----------------------------------------------------+233| ``%(funcName)s`` | Name of function containing the logging call. |234+------------------+----------------------------------------------------+235| ``%(lineno)d`` | Source line number where the logging call was |236| | issued (if available). |237+------------------+----------------------------------------------------+238| ``%(asctime)s`` | Human-readable time when the LogRecord` was |239| | created. By default this is of the form |240| | ``"2003-07-08 16:49:45,896"`` (the numbers after |241| | the comma are millisecond portion of the time). |242| | This can be changed by subclassing the formatter |243| | and overriding the |244| | :meth:`~logging.Formatter.formatTime` method. |245+------------------+----------------------------------------------------+246| ``%(message)s`` | The logged message, computed as ``msg % args`` |247+------------------+----------------------------------------------------+248249If you want to further customize the formatting, you can subclass the250formatter. The formatter has three interesting methods:251252:meth:`~logging.Formatter.format`:253 handles the actual formatting. It is passed a254 :class:`~logging.LogRecord` object and has to return the formatted255 string.256:meth:`~logging.Formatter.formatTime`:257 called for `asctime` formatting. If you want a different time format258 you can override this method.259:meth:`~logging.Formatter.formatException`260 called for exception formatting. It is passed an :attr:`~sys.exc_info`261 tuple and has to return a string. The default is usually fine, you262 don't have to override it.263264For more information, head over to the official documentation.265266267Other Libraries268---------------269270So far we only configured the logger your application created itself.271Other libraries might log themselves as well. For example, SQLAlchemy uses272logging heavily in its core. While there is a method to configure all273loggers at once in the :mod:`logging` package, I would not recommend using274it. There might be a situation in which you want to have multiple275separate applications running side by side in the same Python interpreter276and then it becomes impossible to have different logging setups for those.277278Instead, I would recommend figuring out which loggers you are interested279in, getting the loggers with the :func:`~logging.getLogger` function and280iterating over them to attach handlers::281282 from logging import getLogger283 loggers = [app.logger, getLogger('sqlalchemy'),284 getLogger('otherlibrary')]285 for logger in loggers:286 logger.addHandler(mail_handler)287 logger.addHandler(file_handler)288289290Debugging Application Errors291============================292293For production applications, configure your application with logging and294notifications as described in :ref:`application-errors`. This section provides295pointers when debugging deployment configuration and digging deeper with a296full-featured Python debugger.297298299When in Doubt, Run Manually300---------------------------301302Having problems getting your application configured for production? If you303have shell access to your host, verify that you can run your application304manually from the shell in the deployment environment. Be sure to run under305the same user account as the configured deployment to troubleshoot permission306issues. You can use Flask's builtin development server with `debug=True` on307your production host, which is helpful in catching configuration issues, but308**be sure to do this temporarily in a controlled environment.** Do not run in309production with `debug=True`.310311312.. _working-with-debuggers:313314Working with Debuggers315----------------------316317To dig deeper, possibly to trace code execution, Flask provides a debugger out318of the box (see :ref:`debug-mode`). If you would like to use another Python319debugger, note that debuggers interfere with each other. You have to set some320options in order to use your favorite debugger:321322* ``debug`` - whether to enable debug mode and catch exceptions323* ``use_debugger`` - whether to use the internal Flask debugger324* ``use_reloader`` - whether to reload and fork the process on exception325326``debug`` must be True (i.e., exceptions must be caught) in order for the other327two options to have any value.328329If you're using Aptana/Eclipse for debugging you'll need to set both330``use_debugger`` and ``use_reloader`` to False.331332A possible useful pattern for configuration is to set the following in your333config.yaml (change the block as appropriate for your application, of course)::334335 FLASK:336 DEBUG: True337 DEBUG_WITH_APTANA: True338339Then in your application's entry-point (main.py), you could have something like::340341 if __name__ == "__main__":342 # To allow aptana to receive errors, set use_debugger=False343 app = create_app(config="config.yaml")344345 if app.debug: use_debugger = True346 try:347 # Disable Flask's debugger if external debugger is requested348 use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))349 except:350 pass351 app.run(use_debugger=use_debugger, debug=app.debug,352 use_reloader=use_debugger, host='0.0.0.0')