New in version 0.3.

Applications fail, servers fail. Sooner or later you will see an exception in production. Even if your code is 100% correct, you will still see exceptions from time to time. Why? Because everything else involved will fail. Here are some situations where perfectly fine code can lead to server errors:

  • 客户端提前终止请求,而应用依然在读取进来的数据
  • the database server was overloaded and could not handle the query
  • a filesystem is full
  • a harddrive crashed
  • a backend server overloaded
  • a programming error in a library you are using
  • network connection of the server to another system failed

And that’s just a small sample of issues you could be facing. So how do we deal with that sort of problem? By default if your application runs in production mode, Flask will display a very simple page for you and log the exception to the logger.

But there is more you can do, and we will cover some better setups to deal with errors.


发送错误邮件,即使只是关键的邮件,可能会变得压倒性,如果足够的用户击中错误,日志文件通常从来没有看过。This is why we recommend using Sentry for dealing with application errors. It’s available as an Open Source project on GitHub and is also available as a hosted version which you can try for free. Sentry aggregates duplicate errors, captures the full stack trace and local variables for debugging, and sends you mails based on new errors or frequency thresholds.

To use Sentry you need to install the raven client:

$ pip install raven

And then add this to your Flask app:

from raven.contrib.flask import Sentry
sentry = Sentry(app, dsn='YOUR_DSN_HERE')

Or if you are using factories you can also init it later:

from raven.contrib.flask import Sentry
sentry = Sentry(dsn='YOUR_DSN_HERE')

def create_app():
    app = Flask(__name__)
    return app

The YOUR_DSN_HERE value needs to be replaced with the DSN value you get from your Sentry installation.

Afterwards failures are automatically reported to Sentry and from there you can receive error notifications.






def handle_bad_request(e):
    return 'bad request!'

app.register_error_handler(400, lambda e: 'bad request!')

Those two ways are equivalent, but the first one is more clear and leaves you with a function to call on your whim (and in tests). Note that werkzeug.exceptions.HTTPException subclasses like BadRequest from the example and their HTTP codes are interchangeable when handed to the registration methods or decorator (BadRequest.code == 400).


Changed in version 0.11: Errorhandlers are now prioritized by specificity of the exception classes they are registered for instead of the order they are registered in.


Once an exception instance is raised, its class hierarchy is traversed, and searched for in the exception classes for which handlers are registered. The most specific handler is selected.



If the application runs in production mode (which it will do on your server) you might not see any log messages. 原因是Flask默认只报告给WSGI错误流或stderr(取决于哪一个可用)。Where this ends up is sometimes hard to find. Often it’s in your webserver’s log files.

I can pretty much promise you however that if you only use a logfile for the application errors you will never look at it except for debugging an issue when a user reported it for you. What you probably want instead is a mail the second the exception happened. Then you get an alert and you can do something about it.

Flask uses the Python builtin logging system, and it can actually send you mails for errors which is probably what you want. Here is how you can configure the Flask logger to send you mails for exceptions:

ADMINS = ['yourname@example.com']
if not app.debug:
    import logging
    from logging.handlers import SMTPHandler
    mail_handler = SMTPHandler('',
                               ADMINS, 'YourApplication Failed')

So what just happened? 我们创建了一个新的SMTPHandler用来监听127.0.0.1的邮件服务器向所有的ADMINS发送发件人为server-error@example.com,主题为 “YourApplication Failed” 的邮件。If your mail server requires credentials, these can also be provided. 详情请见SMTPHandler的文档。

We also tell the handler to only send errors and more critical messages. Because we certainly don’t want to get a mail for warnings or other useless logs that might happen during request handling.

Before you run that in production, please also look at Controlling the Log Format to put more information into that error mail. 这将节省你很多弯路。


即便你收到邮件,你可能还是想用日志记录警告信息。当调试问题的时候,收集更多的信息是个好主意。Flask 0.11在默认情况下,错误信息会自动记录到网站服务器的日志中。但是警告信息不会。请注意Flask本身在其核心系统不会发出任何警告级别的信息,所以如果发生奇怪的事情,在代码中打印警告信息是你的责任。

There are a couple of handlers provided by the logging system out of the box but not all of them are useful for basic error logging. The most interesting are probably the following:

  • FileHandler——记录日志到文件系统上的文件中。
  • RotatingFileHandler——记录日志到文件系统的文件中,并在一定数量的消息后rotate。
  • NTEventLogHandler - will log to the system event log of a Windows system. If you are deploying on a Windows box, this is what you want to use.
  • SysLogHandler - sends logs to a UNIX syslog.

Once you picked your log handler, do like you did with the SMTP handler above, just make sure to use a lower setting (I would recommend WARNING):

if not app.debug:
    import logging
    from themodule import TheHandlerYouWant
    file_handler = TheHandlerYouWant(...)


默认情况下,错误处理只会把消息字符串记录到文件或邮件发送给你。A log record stores more information, and it makes a lot of sense to configure your logger to also contain that information so that you have a better idea of why that error happened, and more importantly, where it did.

A formatter can be instantiated with a format string. 注意回溯会自动附加到日志条目后。你不需要在日志格式的格式化字符串中这么做。

Here some example setups:


from logging import Formatter
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Module:             %(module)s
Function:           %(funcName)s
Time:               %(asctime)s




from logging import Formatter
    '%(asctime)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'


Here is a list of useful formatting variables for the format string. 注意这个列表并不完整,完整的列表请翻阅logging包的官方文档。

%(pathname)sFull pathname of the source file where the logging call was issued (if available).
%(filename)sFilename portion of pathname.
%(module)sModule (name portion of filename).
%(funcName)sName of function containing the logging call.
%(lineno)dSource line number where the logging call was issued (if available).
%(asctime)sogRecord创建时人类可读的时间格式。By default this is of the form "2003-07-08 16:49:45,896" (the numbers after the comma are millisecond portion of the time). This can be changed by subclassing the formatter and overriding the formatTime() method.
%(message)sThe logged message, computed as msg % args

如果你想深度定制日志格式,你可以继承 Formatter 。Formatter有三个需要关注的方法:

handles the actual formatting. It is passed a LogRecord object and has to return the formatted string.
called for asctime formatting. If you want a different time format you can override this method.
called for exception formatting. It is passed an exc_info tuple and has to return a string. The default is usually fine, you don’t have to override it.

For more information, head over to the official documentation.


So far we only configured the logger your application created itself. Other libraries might log themselves as well. For example, SQLAlchemy uses logging heavily in its core. 虽然在logging包中有一个方法可以一次性配置所有的日志记录器,我不推荐使用它。There might be a situation in which you want to have multiple separate applications running side by side in the same Python interpreter and then it becomes impossible to have different logging setups for those.

作为替代,我推荐你找出你有兴趣的日志记录器,用getLogger() 函数来获取日志记录器,并且遍历它们来附加处理程序:

from logging import getLogger
loggers = [app.logger, getLogger('sqlalchemy'),
for logger in loggers:


For production applications, configure your application with logging and notifications as described in Application Errors. This section provides pointers when debugging deployment configuration and digging deeper with a full-featured Python debugger.


Having problems getting your application configured for production? If you have shell access to your host, verify that you can run your application manually from the shell in the deployment environment. Be sure to run under the same user account as the configured deployment to troubleshoot permission issues. You can use Flask’s builtin development server with debug=True on your production host, which is helpful in catching configuration issues, but be sure to do this temporarily in a controlled environment. Do not run in production with debug=True.


To dig deeper, possibly to trace code execution, Flask provides a debugger out of the box (see Debug Mode). If you would like to use another Python debugger, note that debuggers interfere with each other. You have to set some options in order to use your favorite debugger:

  • debug - whether to enable debug mode and catch exceptions
  • use_debugger - whether to use the internal Flask debugger
  • use_reloader - whether to reload and fork the process on exception

debug必须为 True (即异常必须被捕获)来允许其它的两个选项设置为任何值。

If you’re using Aptana/Eclipse for debugging you’ll need to set both use_debugger and use_reloader to False.

A possible useful pattern for configuration is to set the following in your config.yaml (change the block as appropriate for your application, of course):

    DEBUG: True

Then in your application’s entry-point (main.py), you could have something like:

if __name__ == "__main__":
    # To allow aptana to receive errors, set use_debugger=False
    app = create_app(config="config.yaml")

    if app.debug: use_debugger = True
        # Disable Flask's debugger if external debugger is requested
        use_debugger = not(app.config.get('DEBUG_WITH_APTANA'))
    app.run(use_debugger=use_debugger, debug=app.debug,
            use_reloader=use_debugger, host='')