Skip to content
Myr

errorhandling.rst

This file

Path

docs/errorhandling.rst

301 lines · 12.2 KiB

Last changed by

Updated the logging documentation for recent changes.Armin Ronacherbefore adoption7c16054

History of this file

Take 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 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 Mails32-----------3334If the application runs in production mode (which it will do on your35server) you might not see any log messages.  The reason for that is that36Flask by default will just report to the WSGI error stream or stderr37(depending on what's available).  Where this ends up is sometimes hard to38find.  Often it's in your webserver's log files.3940I can pretty much promise you however that if you only use a logfile for41the application errors you will never look at it except for debugging an42issue when a user reported it for you.  What you probably want instead is43a mail the second the exception happened.  Then you get an alert and you44can do something about it.4546Flask uses the Python builtin logging system, and it can actually send47you mails for errors which is probably what you want.  Here is how you can48configure the Flask logger to send you mails for exceptions::4950    ADMINS = ['yourname@example.com']51    if not app.debug:52        import logging53        from logging.handlers import SMTPHandler54        mail_handler = SMTPHandler('127.0.0.1',55                                   'server-error@example.com',56                                   ADMINS, 'YourApplication Failed')57        mail_handler.setLevel(logging.ERROR)58        app.logger.addHandler(mail_handler)5960So what just happened?  We created a new61:class:`~logging.handlers.SMTPHandler` that will send mails with the mail62server listening on ``127.0.0.1`` to all the `ADMINS` from the address63*server-error@example.com* with the subject "YourApplication Failed".  If64your mail server requires credentials, these can also be provided.  For65that check out the documentation for the66:class:`~logging.handlers.SMTPHandler`.6768We also tell the handler to only send errors and more critical messages.69Because we certainly don't want to get a mail for warnings or other70useless logs that might happen during request handling.7172Before you run that in production, please also look at :ref:`logformat` to73put more information into that error mail.  That will save you from a lot74of frustration.757677Logging to a File78-----------------7980Even if you get mails, you probably also want to log warnings.  It's a81good idea to keep as much information around that might be required to82debug a problem.  By default as of Flask 1.0, errors are logged to your83webserver's log automatically.  Warnings however are not.  Please note84that Flask itself will not issue any warnings in the core system, so it's85your responsibility to warn in the code if something seems odd.8687There are a couple of handlers provided by the logging system out of the88box but not all of them are useful for basic error logging.  The most89interesting are probably the following:9091-   :class:`~logging.FileHandler` - logs messages to a file on the92    filesystem.93-   :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file94    on the filesystem and will rotate after a certain number of messages.95-   :class:`~logging.handlers.NTEventLogHandler` - will log to the system96    event log of a Windows system.  If you are deploying on a Windows box,97    this is what you want to use.98-   :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX99    syslog.100101Once you picked your log handler, do like you did with the SMTP handler102above, just make sure to use a lower setting (I would recommend103`WARNING`)::104105    if not app.debug:106        import logging107        from themodule import TheHandlerYouWant108        file_handler = TheHandlerYouWant(...)109        file_handler.setLevel(logging.WARNING)110        app.logger.addHandler(file_handler)111112.. _logformat:113114Controlling the Log Format115--------------------------116117By default a handler will only write the message string into a file or118send you that message as mail.  A log record stores more information,119and it makes a lot of sense to configure your logger to also contain that120information so that you have a better idea of why that error happened, and121more importantly, where it did.122123A formatter can be instantiated with a format string.  Note that124tracebacks are appended to the log entry automatically.  You don't have to125do that in the log formatter format string.126127Here some example setups:128129Email130`````131132::133134    from logging import Formatter135    mail_handler.setFormatter(Formatter('''136    Message type:       %(levelname)s137    Location:           %(pathname)s:%(lineno)d138    Module:             %(module)s139    Function:           %(funcName)s140    Time:               %(asctime)s141142    Message:143144    %(message)s145    '''))146147File logging148````````````149150::151152    from logging import Formatter153    file_handler.setFormatter(Formatter(154        '%(asctime)s %(levelname)s: %(message)s '155        '[in %(pathname)s:%(lineno)d]'156    ))157158159Complex Log Formatting160``````````````````````161162Here is a list of useful formatting variables for the format string.  Note163that this list is not complete, consult the official documentation of the164:mod:`logging` package for a full list.165166.. tabularcolumns:: |p{3cm}|p{12cm}|167168+------------------+----------------------------------------------------+169| Format           | Description                                        |170+==================+====================================================+171| ``%(levelname)s``| Text logging level for the message                 |172|                  | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,           |173|                  | ``'ERROR'``, ``'CRITICAL'``).                      |174+------------------+----------------------------------------------------+175| ``%(pathname)s`` | Full pathname of the source file where the         |176|                  | logging call was issued (if available).            |177+------------------+----------------------------------------------------+178| ``%(filename)s`` | Filename portion of pathname.                      |179+------------------+----------------------------------------------------+180| ``%(module)s``   | Module (name portion of filename).                 |181+------------------+----------------------------------------------------+182| ``%(funcName)s`` | Name of function containing the logging call.      |183+------------------+----------------------------------------------------+184| ``%(lineno)d``   | Source line number where the logging call was      |185|                  | issued (if available).                             |186+------------------+----------------------------------------------------+187| ``%(asctime)s``  | Human-readable time when the LogRecord` was        |188|                  | created.  By default this is of the form           |189|                  | ``"2003-07-08 16:49:45,896"`` (the numbers after   |190|                  | the comma are millisecond portion of the time).    |191|                  | This can be changed by subclassing the formatter   |192|                  | and overriding the                                 |193|                  | :meth:`~logging.Formatter.formatTime` method.      |194+------------------+----------------------------------------------------+195| ``%(message)s``  | The logged message, computed as ``msg % args``     |196+------------------+----------------------------------------------------+197198If you want to further customize the formatting, you can subclass the199formatter.  The formatter has three interesting methods:200201:meth:`~logging.Formatter.format`:202    handles the actual formatting.  It is passed a203    :class:`~logging.LogRecord` object and has to return the formatted204    string.205:meth:`~logging.Formatter.formatTime`:206    called for `asctime` formatting.  If you want a different time format207    you can override this method.208:meth:`~logging.Formatter.formatException`209    called for exception formatting.  It is passed an :attr:`~sys.exc_info`210    tuple and has to return a string.  The default is usually fine, you211    don't have to override it.212213For more information, head over to the official documentation.214215216Other Libraries217---------------218219So far we only configured the logger your application created itself.220Other libraries might log themselves as well.  For example, SQLAlchemy uses221logging heavily in its core.  While there is a method to configure all222loggers at once in the :mod:`logging` package, I would not recommend using223it.  There might be a situation in which you want to have multiple224separate applications running side by side in the same Python interpreter225and then it becomes impossible to have different logging setups for those.226227Instead, I would recommend figuring out which loggers you are interested228in, getting the loggers with the :func:`~logging.getLogger` function and229iterating over them to attach handlers::230231    from logging import getLogger232    loggers = [app.logger, getLogger('sqlalchemy'),233               getLogger('otherlibrary')]234    for logger in loggers:235        logger.addHandler(mail_handler)236        logger.addHandler(file_handler)237238239Debugging Application Errors240============================241242For production applications, configure your application with logging and243notifications as described in :ref:`application-errors`.  This section provides244pointers when debugging deployment configuration and digging deeper with a245full-featured Python debugger.246247248When in Doubt, Run Manually249---------------------------250251Having problems getting your application configured for production?  If you252have shell access to your host, verify that you can run your application253manually from the shell in the deployment environment.  Be sure to run under254the same user account as the configured deployment to troubleshoot permission255issues.  You can use Flask's builtin development server with `debug=True` on256your production host, which is helpful in catching configuration issues, but257**be sure to do this temporarily in a controlled environment.** Do not run in258production with `debug=True`.259260261.. _working-with-debuggers:262263Working with Debuggers264----------------------265266To dig deeper, possibly to trace code execution, Flask provides a debugger out267of the box (see :ref:`debug-mode`).  If you would like to use another Python268debugger, note that debuggers interfere with each other.  You have to set some269options in order to use your favorite debugger:270271* ``debug``        - whether to enable debug mode and catch exceptions272* ``use_debugger`` - whether to use the internal Flask debugger273* ``use_reloader`` - whether to reload and fork the process on exception274275``debug`` must be True (i.e., exceptions must be caught) in order for the other276two options to have any value.277278If you're using Aptana/Eclipse for debugging you'll need to set both279``use_debugger`` and ``use_reloader`` to False.280281A possible useful pattern for configuration is to set the following in your282config.yaml (change the block as appropriate for your application, of course)::283284   FLASK:285       DEBUG: True286       DEBUG_WITH_APTANA: True287288Then in your application's entry-point (main.py), you could have something like::289290   if __name__ == "__main__":291       # To allow aptana to receive errors, set use_debugger=False292       app = create_app(config="config.yaml")293294       if app.debug: use_debugger = True295       try:296           # Disable Flask's debugger if external debugger is requested297           use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))298       except:299           pass300       app.run(use_debugger=use_debugger, debug=app.debug,301               use_reloader=use_debugger, host='0.0.0.0')