errorhandling.rst
This file
Path
docs/errorhandling.rst
302 lines · 12.2 KiB
Last changed by
Update docs/errorhandling.rstAndrew Ashbefore adoptionfc7fe62
History of this fileTake it
1.. _application-errors:23Logging Application 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 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 data.16- the database server was overloaded and could not handle the query.17- 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 failed.2223And 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 Mails32-----------3334If the application runs in production mode (which it will do on your35server) you won't see any log messages by default. Why is that? Flask36tries to be a zero-configuration framework. Where should it drop the logs37for you if there is no configuration? Guessing is not a good idea because38chances are, the place it guessed is not the place where the user has39permission to create a logfile. Also, for most small applications nobody40will look at the logs anyways.4142In fact, I promise you right now that if you configure a logfile for the43application errors you will never look at it except for debugging an issue44when a user reported it for you. What you want instead is a mail the45second the exception happened. Then you get an alert and you can do46something about it.4748Flask uses the Python builtin logging system, and it can actually send49you mails for errors which is probably what you want. Here is how you can50configure the Flask logger to send you mails for exceptions::5152 ADMINS = ['yourname@example.com']53 if not app.debug:54 import logging55 from logging.handlers import SMTPHandler56 mail_handler = SMTPHandler('127.0.0.1',57 'server-error@example.com',58 ADMINS, 'YourApplication Failed')59 mail_handler.setLevel(logging.ERROR)60 app.logger.addHandler(mail_handler)6162So what just happened? We created a new63:class:`~logging.handlers.SMTPHandler` that will send mails with the mail64server listening on ``127.0.0.1`` to all the `ADMINS` from the address65*server-error@example.com* with the subject "YourApplication Failed". If66your mail server requires credentials, these can also be provided. For67that check out the documentation for the68:class:`~logging.handlers.SMTPHandler`.6970We also tell the handler to only send errors and more critical messages.71Because we certainly don't want to get a mail for warnings or other72useless logs that might happen during request handling.7374Before you run that in production, please also look at :ref:`logformat` to75put more information into that error mail. That will save you from a lot76of frustration.777879Logging to a File80-----------------8182Even if you get mails, you probably also want to log warnings. It's a83good idea to keep as much information around that might be required to84debug a problem. Please note that Flask itself will not issue any85warnings in the core system, so it's your responsibility to warn in the86code if something seems odd.8788There are a couple of handlers provided by the logging system out of the89box but not all of them are useful for basic error logging. The most90interesting are probably the following:9192- :class:`~logging.FileHandler` - logs messages to a file on the93 filesystem.94- :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file95 on the filesystem and will rotate after a certain number of messages.96- :class:`~logging.handlers.NTEventLogHandler` - will log to the system97 event log of a Windows system. If you are deploying on a Windows box,98 this is what you want to use.99- :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX100 syslog.101102Once you picked your log handler, do like you did with the SMTP handler103above, just make sure to use a lower setting (I would recommend104`WARNING`)::105106 if not app.debug:107 import logging108 from themodule import TheHandlerYouWant109 file_handler = TheHandlerYouWant(...)110 file_handler.setLevel(logging.WARNING)111 app.logger.addHandler(file_handler)112113.. _logformat:114115Controlling the Log Format116--------------------------117118By default a handler will only write the message string into a file or119send you that message as mail. A log record stores more information,120and it makes a lot of sense to configure your logger to also contain that121information so that you have a better idea of why that error happened, and122more importantly, where it did.123124A formatter can be instantiated with a format string. Note that125tracebacks are appended to the log entry automatically. You don't have to126do that in the log formatter format string.127128Here some example setups:129130Email131`````132133::134135 from logging import Formatter136 mail_handler.setFormatter(Formatter('''137 Message type: %(levelname)s138 Location: %(pathname)s:%(lineno)d139 Module: %(module)s140 Function: %(funcName)s141 Time: %(asctime)s142143 Message:144145 %(message)s146 '''))147148File logging149````````````150151::152153 from logging import Formatter154 file_handler.setFormatter(Formatter(155 '%(asctime)s %(levelname)s: %(message)s '156 '[in %(pathname)s:%(lineno)d]'157 ))158159160Complex Log Formatting161``````````````````````162163Here is a list of useful formatting variables for the format string. Note164that this list is not complete, consult the official documentation of the165:mod:`logging` package for a full list.166167.. tabularcolumns:: |p{3cm}|p{12cm}|168169+------------------+----------------------------------------------------+170| Format | Description |171+==================+====================================================+172| ``%(levelname)s``| Text logging level for the message |173| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |174| | ``'ERROR'``, ``'CRITICAL'``). |175+------------------+----------------------------------------------------+176| ``%(pathname)s`` | Full pathname of the source file where the |177| | logging call was issued (if available). |178+------------------+----------------------------------------------------+179| ``%(filename)s`` | Filename portion of pathname. |180+------------------+----------------------------------------------------+181| ``%(module)s`` | Module (name portion of filename). |182+------------------+----------------------------------------------------+183| ``%(funcName)s`` | Name of function containing the logging call. |184+------------------+----------------------------------------------------+185| ``%(lineno)d`` | Source line number where the logging call was |186| | issued (if available). |187+------------------+----------------------------------------------------+188| ``%(asctime)s`` | Human-readable time when the LogRecord` was |189| | created. By default this is of the form |190| | ``"2003-07-08 16:49:45,896"`` (the numbers after |191| | the comma are millisecond portion of the time). |192| | This can be changed by subclassing the formatter |193| | and overriding the |194| | :meth:`~logging.Formatter.formatTime` method. |195+------------------+----------------------------------------------------+196| ``%(message)s`` | The logged message, computed as ``msg % args`` |197+------------------+----------------------------------------------------+198199If you want to further customize the formatting, you can subclass the200formatter. The formatter has three interesting methods:201202:meth:`~logging.Formatter.format`:203 handles the actual formatting. It is passed a204 :class:`~logging.LogRecord` object and has to return the formatted205 string.206:meth:`~logging.Formatter.formatTime`:207 called for `asctime` formatting. If you want a different time format208 you can override this method.209:meth:`~logging.Formatter.formatException`210 called for exception formatting. It is passed an :attr:`~sys.exc_info`211 tuple and has to return a string. The default is usually fine, you212 don't have to override it.213214For more information, head over to the official documentation.215216217Other Libraries218---------------219220So far we only configured the logger your application created itself.221Other libraries might log themselves as well. For example, SQLAlchemy uses222logging heavily in its core. While there is a method to configure all223loggers at once in the :mod:`logging` package, I would not recommend using224it. There might be a situation in which you want to have multiple225separate applications running side by side in the same Python interpreter226and then it becomes impossible to have different logging setups for those.227228Instead, I would recommend figuring out which loggers you are interested229in, getting the loggers with the :func:`~logging.getLogger` function and230iterating over them to attach handlers::231232 from logging import getLogger233 loggers = [app.logger, getLogger('sqlalchemy'),234 getLogger('otherlibrary')]235 for logger in loggers:236 logger.addHandler(mail_handler)237 logger.addHandler(file_handler)238239240Debugging Application Errors241============================242243For production applications, configure your application with logging and244notifications as described in :ref:`application-errors`. This section provides245pointers when debugging deployment configuration and digging deeper with a246full-featured Python debugger.247248249When in Doubt, Run Manually250---------------------------251252Having problems getting your application configured for production? If you253have shell access to your host, verify that you can run your application254manually from the shell in the deployment environment. Be sure to run under255the same user account as the configured deployment to troubleshoot permission256issues. You can use Flask's builtin development server with `debug=True` on257your production host, which is helpful in catching configuration issues, but258**be sure to do this temporarily in a controlled environment.** Do not run in259production with `debug=True`.260261262.. _working-with-debuggers:263264Working with Debuggers265----------------------266267To dig deeper, possibly to trace code execution, Flask provides a debugger out268of the box (see :ref:`debug-mode`). If you would like to use another Python269debugger, note that debuggers interfere with each other. You have to set some270options in order to use your favorite debugger:271272* ``debug`` - whether to enable debug mode and catch exceptinos273* ``use_debugger`` - whether to use the internal Flask debugger274* ``use_reloader`` - whether to reload and fork the process on exception275276``debug`` must be True (i.e., exceptions must be caught) in order for the other277two options to have any value.278279If you're using Aptana/Eclipse for debugging you'll need to set both280``use_debugger`` and ``use_reloader`` to False.281282A possible useful pattern for configuration is to set the following in your283config.yaml (change the block as appropriate for your application, of course)::284285 FLASK:286 DEBUG: True287 DEBUG_WITH_APTANA: True288289Then in your application's entry-point (main.py), you could have something like::290291 if __name__ == "__main__":292 # To allow aptana to receive errors, set use_debugger=False293 app = create_app(config="config.yaml")294295 if app.debug: use_debugger = True296 try:297 # Disable Flask's debugger if external debugger is requested298 use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))299 except:300 pass301 app.run(use_debugger=use_debugger, debug=app.debug,302 use_reloader=use_debugger, host='0.0.0.0')