Skip to content
Myr

Added a documentation chapter about logging

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent e7f67e1 · Browse files · 9 files+306 added−10 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+306 added−10 removed

  • tests:+22 added−0 removed
  • other:+284 added−10 removed

9 files+306 added−10 removed

modified:docs/_templates/sidebarintro.html+4 added-1 removed
modified:docs/patterns/fileuploads.rst+2 added
1.. _uploading-files:23Uploading Files4===============56Ah yes, the good old problem of file uploads. The basic idea of file
154 unmodified lines
modified:docs/_themesnot shown

Its text is not shown, modified.

modified:docs/conf.py+2 added
48 unmodified lines
49# |version| and |release|, also used in various other places throughout the50# built documents.51release = __import__('pkg_resources').get_distribution('Flask').version52version = '.'.join(release.split('.')[:2])53if 'dev' in version:54 version = version.split('dev')[0]5556# The language for content autogenerated by Sphinx. Refer to documentation57# for a list of supported languages.58#language = None
182 unmodified lines
modified:docs/contents.rst.inc+1 added
11 unmodified lines
12 installation13 quickstart14 tutorial/index15 testing16 errorhandling17 patterns/index18 deploying/index19 becomingbig20
22 unmodified lines
added:docs/errorhandling.rst+232 added
1Handling Application Errors2===========================34.. versionadded:: 0.556Applications fail, server fail. Sooner or later you will see an exception7in production. Even if your code is 100% correct, you will still see8exceptions from time to time. Why? Because everything else involved will9fail. Here some situations where perfectly fine code can lead to server10errors:1112- the client terminated the request early and the application was still13 reading from the incoming data.14- the database server was overloaded and could not handle the query.15- a filesystem is full16- a harddrive crashed17- a backend server overloaded18- a programming error in a library you are using19- network connection of the server to another system failed.2021And that's just a small sample of issues you could be facing. So how to22deal with that sort of problem? By default if your application runs in23production mode, Flask will display a very simple page for you and log the24exception to the :attr:`~flask.Flask.logger`.2526But there is more you can do, and we will cover some better setups to deal27with errors.2829Error Mails30-----------3132If the application runs in production mode (which it will do on your33server) you won't see any log messages by default. Why that? Flask tries34to be a zero-configuration framework and where should it drop the logs for35you if there is no configuration. Guessing is not a good idea because36changes are, the place it guessed is not the place where the user has the37permission to create a logfile. Also, for most small applications nobody38will look at the logs anyways.3940In fact, I promise you right now that if you configure a logfile for the41application errors you will never look at it except for debugging an issue42when a user reported it for you. What you want instead is a mail the43second the exception happened. Then you get an alert and you can do44something about it.4546Flask is using the Python builtin logging system and that one can actually47send you mails for errors which is probably what you want. Here is how48you can configure 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 provided, for that65check out the documentation for the :class:`~logging.handlers.SMTPHandler`.6667We also tell the handler to only send errors and more critical messages.68Because we certainly don't want to get a mail for warnings or other69useless logs that might happen during request handling.7071Before you run that in production, please also look at :ref:`log-format`72to put more information into that error mail. That will save you from a73lot of frustration.747576Logging to a File77-----------------7879Even if you get mails, you probably also want to log warnings. It's a80good idea to keep as much information around that might be required to81debug a problem. Please note that Flask itself will not issue any82warnings in the core system, so it's your responsibility to warn in the83code if something seems odd.8485There are a couple of handlers provided by the logging system out of the86box but not all of them are useful for basic error logging. The most87interesting are probably the following:8889- :class:`~logging.handlers.FileHandler` - logs messages to a file on the90 filesystem.91- :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file92 on the filesystem and will rotate after a certain number of messages.93- :class:`~logging.handlers.NTEventLogHandler` - will log to the system94 event log of a Windows system. If you are deploying on a Windows box,95 this is what you want to use.96- :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX97 syslog.9899Once you picked your log handler, do like you did with the SMTP handler100above, just make sure to use a lower setting (I would recommend101`WARNING`)::102103 if not app.debug:104 import logging105 from logging.handlers import TheHandlerYouWant106 file_handler = TheHandlerYouWant(...)107 file_handler.setLevel(logging.WARNING)108 app.logger.addHandler(file_handler)109110.. _log-format:111112Controlling the Log Format113--------------------------114115By default a handler will only write the message string into a file or116send you that message as mail. But a log record stores more information117and it makes a lot of sense to configure your logger to also contain that118information so that you have a better idea of why that error happened, and119more importantly, where it did.120121A formatter can be instanciated with a format string. Note that122tracebacks are appended to the log entry automatically. You don't have to123do that in the log formatter format string.124125Here some example setups:126127Email128`````129130::131132 from logging import Formatter133 mail_handler.setFormatter(Formatter('''134 Message type: %(levelname)s135 Location: %(pathname)s:%(lineno)d136 Module: %(module)s137 Function: %(funcName)s138 Time: %(asctime)s139140 Message:141142 %(message)s143 '''))144145File logging146````````````147148::149150 from logging import Formatter151 file_handler.setFormatter(Formatter(152 '%(astime)s %(levelname)s: %(message)s '153 '[in %(pathname)s:%(lineno)d]'154 ))155156157Complex Log Formatting158``````````````````````159160Here is a list of useful formatting variables for the format string. Note161that this list is not complete, consult the official documentation of the162:mod:`logging` package for a full list.163164+------------------+----------------------------------------------------+165| Format | Description |166+==================+====================================================+167| ``%(levelname)s``| Text logging level for the message |168| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |169| | ``'ERROR'``, ``'CRITICAL'``). |170+------------------+----------------------------------------------------+171| ``%(pathname)s`` | Full pathname of the source file where the |172| | logging call was issued (if available). |173+------------------+----------------------------------------------------+174| ``%(filename)s`` | Filename portion of pathname. |175+------------------+----------------------------------------------------+176| ``%(module)s`` | Module (name portion of filename). |177+------------------+----------------------------------------------------+178| ``%(funcName)s`` | Name of function containing the logging call. |179+------------------+----------------------------------------------------+180| ``%(lineno)d`` | Source line number where the logging call was |181| | issued (if available). |182+------------------+----------------------------------------------------+183| ``%(asctime)s`` | Human-readable time when the LogRecord` was |184| | created. By default this is of the form |185| | ``"2003-07-08 16:49:45,896"`` (the numbers after |186| | the comma are millisecond portion of the time). |187| | This can be changed by subclassing the formatter |188| | and overriding the |189| | :meth:`~logging.Formatter.formatTime` method. |190+------------------+----------------------------------------------------+191| ``%(message)s`` | The logged message, computed as ``msg % args`` |192+------------------+----------------------------------------------------+193194If you want to further customize the formatting, you can subclass the195formatter. The formatter has three interesting methods:196197:meth:`~logging.Formatter.format`:198 handles the actual formatting. It is passed a199 :class:`~logging.LogRecord` object and has to return the formatted200 string.201:meth:`~logging.Formatter.formatTime`:202 called for `asctime` formatting. If you want a different time format203 you can override this method.204:meth:`~logging.Formatter.formatException`205 called for exception formatting. It is passed a :attr:`~sys.exc_info`206 tuple and has to return a string. The default is usually fine, you207 don't have to override it.208209For more information, head over to the official documentation.210211212Other Libraries213---------------214215So far we only configured the logger your application created itself.216Other libraries might log themselves as well. For example, SQLAlchemy use217logging heavily in the core. While there is a method to configure all218loggers at once in the :mod:`logging` package, I would not recommend using219it. There might be a situation in which you want to have multiple220separate applications running side by side in the same Python interpreter221and then it becomes impossible to have different logging setups for those.222223Instead, I would recommend figuring out which loggers you are interested224in, getting the loggers with the :func:`~logging.getLogger` function and225iterating over them to attach handlers::226227 from logging import getLogger228 loggers = [app.logger, getLogger('sqlalchemy'),229 getLogger('otherlibrary')]230 for logger in loggers:231 logger.addHandler(mail_handler)232 logger.addHandler(file_handler)
modified:docs/quickstart.rst+28 added
530 unmodified lines
531 f= request.files['the_file']532 f.save('/var/www/uploads/' + secure_filename(f.filename))533 ...534535For some better examples, checkout the :ref:`uploading-files` pattern.536537Cookies538```````539540To access cookies you can use the :attr:`~flask.request.cookies`
99 unmodified lines
640To flash a message use the :func:`~flask.flash` method, to get hold of the641messages you can use :func:`~flask.get_flashed_messages` which is also642available in the templates. Check out the :ref:`message-flashing-pattern`643for a full example.644645Logging646-------647648.. versionadded:: 0.5649650Sometimes you might be in the situation where you deal with data that651should be correct, but actually is not. For example you have some client652side code that sends an HTTP request to the server, and it's obviously653malformed. This might be caused by a user tempering with the data, or the654client code failed. Most the time, it's okay to reply with ``400 Bad655Request`` in that situation, but other times it is not and the code has to656continue working.657658Yet you want to log that something fishy happened. This is where loggers659come in handy. As of Flask 0.5 a logger is preconfigured for you to use.660661Here are some example log calls::662663 app.logger.debug('A value for debugging')664 app.logger.warning('A warning ocurred (%d apples)', 42)665 app.logger.error('An error occoured')666667The attached :attr:`~flask.Flask.logger` is a standard logging668:class:`~logging.Logger`, so head over to the official stdlib669documentation for more information.
modified:tests/flask_tests.py+22 added
643 unmodified lines
644 assert 'Traceback (most recent call last):' in err645 assert '1/0' in err646 assert 'ZeroDivisionError:' in err647648 def test_processor_exceptions(self):649 app = flask.Flask(__name__)650 @app.before_request651 def before_request():652 if trigger == 'before':653 1/0654 @app.after_request655 def after_request(response):656 if trigger == 'after':657 1/0658 return response659 @app.route('/')660 def index():661 return 'Foo'662 @app.errorhandler(500)663 def internal_server_error(e):664 return 'Hello Server Error', 500665 for trigger in 'before', 'after':666 rv = app.test_client().get('/')667 assert rv.status_code == 500668 assert rv.data == 'Hello Server Error'669670671def suite():672 from minitwit_tests import MiniTwitTestCase673 from flaskr_tests import FlaskrTestCase674 suite = unittest.TestSuite()
15 unmodified lines
modified:flask.py+15 added-9 removed
664 unmodified lines
665 #:666 #: .. versionadded:: 0.5667 debug_log_format = (668 '-' * 80 + '\n' +669 '%(levelname)s in %(module)s, %(filename)s:%(lineno)d]:\n' +669 '%(levelname)s in %(module)s, %(pathname)s:%(lineno)d]:\n' +670 '%(message)s\n' +671 '-' * 80672 )673
94 unmodified lines
768 @cached_property769 def logger(self):770 """A :class:`logging.Logger` object for this application. The771 default configuration is to log to stderr if the application is772 in debug mode.772 in debug mode. This logger can be used to (surprise) log messages.773 Here some examples::774775 app.logger.debug('A value for debugging')776 app.logger.warning('A warning ocurred (%d apples)', 42)777 app.logger.error('An error occoured')778 """779 from logging import getLogger, StreamHandler, Formatter, DEBUG780 class DebugHandler(StreamHandler):781 def emit(x, record):
307 unmodified lines
1089 raise req.routing_exception1090 return self.view_functions[req.endpoint](**req.view_args)1091 except HTTPException, e:1092 return self.handle_http_exception(e)1088 except Exception, e:1089 return self.handle_exception(e)10931094 def make_response(self, rv):1095 """Converts the return value from a view function to a real1096 response object that is an instance of :attr:`response_class`.
81 unmodified lines
1178 a list of headers and an optional1179 exception context to start the response1180 """1181 with self.request_context(environ):1182 try:1179 rv = self.preprocess_request()1180 if rv is None:1181 rv = self.dispatch_request()1182 response = self.make_response(rv)1183 response = self.process_response(response)1183 rv = self.preprocess_request()1184 if rv is None:1185 rv = self.dispatch_request()1186 response = self.make_response(rv)1187 response = self.process_response(response)1188 except Exception, e:1189 response = self.make_response(self.handle_exception(e))1190 return response(environ, start_response)11911192 def request_context(self, environ):1193 """Creates a request context from the given environment and binds
31 unmodified lines