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
Provenance
- Commit
ea5e654- Tree
8983912- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e7f67e1
9 files changed+306 added−10 removed
modified:docs/_templates/sidebarintro.html+4 added-1 removed
3 unmodified lines45678891011121314156 unmodified lines3 unmodified lines looking at the documentation of the development version. Things are not stable yet, but if you have some feedback, <a href="mailto:armin.ronacher@active-4.com">let me know</a>.</p><h3>Download Documentation</h3><h3>Other Formats</h3><p> You can download the documentation in other formats as well:</p><ul> <li><a href="http://flask.pocoo.org/docs/flask-docs.pdf">as PDF</a> <li><a href="http://flask.pocoo.org/docs/flask-docs.zip">as zipped HTML</a></ul>6 unmodified linesmodified:docs/patterns/fileuploads.rst+2 added
1+.. _uploading-files:2+3 Uploading Files4 ===============5 6 Ah yes, the good old problem of file uploads. The basic idea of file154 unmodified linesmodified:docs/_themesnot shown
Its text is not shown, modified.
modified:docs/conf.py+2 added
48 unmodified lines49 # |version| and |release|, also used in various other places throughout the50 # built documents.51 release = __import__('pkg_resources').get_distribution('Flask').version52 version = '.'.join(release.split('.')[:2])53+if 'dev' in version:54+ version = version.split('dev')[0]55 56 # The language for content autogenerated by Sphinx. Refer to documentation57 # for a list of supported languages.58 #language = None182 unmodified linesmodified:docs/contents.rst.inc+1 added
11 unmodified lines12 installation13 quickstart14 tutorial/index15 testing16+ errorhandling17 patterns/index18 deploying/index19 becomingbig20 22 unmodified linesadded:docs/errorhandling.rst+232 added
1+Handling Application Errors2+===========================3+4+.. versionadded:: 0.55+6+Applications fail, server fail. Sooner or later you will see an exception7+in production. Even if your code is 100% correct, you will still see8+exceptions from time to time. Why? Because everything else involved will9+fail. Here some situations where perfectly fine code can lead to server10+errors:11+12+- 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.20+21+And that's just a small sample of issues you could be facing. So how to22+deal with that sort of problem? By default if your application runs in23+production mode, Flask will display a very simple page for you and log the24+exception to the :attr:`~flask.Flask.logger`.25+26+But there is more you can do, and we will cover some better setups to deal27+with errors.28+29+Error Mails30+-----------31+32+If the application runs in production mode (which it will do on your33+server) you won't see any log messages by default. Why that? Flask tries34+to be a zero-configuration framework and where should it drop the logs for35+you if there is no configuration. Guessing is not a good idea because36+changes are, the place it guessed is not the place where the user has the37+permission to create a logfile. Also, for most small applications nobody38+will look at the logs anyways.39+40+In fact, I promise you right now that if you configure a logfile for the41+application errors you will never look at it except for debugging an issue42+when a user reported it for you. What you want instead is a mail the43+second the exception happened. Then you get an alert and you can do44+something about it.45+46+Flask is using the Python builtin logging system and that one can actually47+send you mails for errors which is probably what you want. Here is how48+you can configure the Flask logger to send you mails for exceptions::49+50+ 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)59+60+So what just happened? We created a new61+:class:`~logging.handlers.SMTPHandler` that will send mails with the mail62+server listening on ``127.0.0.1`` to all the `ADMINS` from the address63+*server-error@example.com* with the subject "YourApplication Failed". If64+your mail server requires credentials these can also provided, for that65+check out the documentation for the :class:`~logging.handlers.SMTPHandler`.66+67+We also tell the handler to only send errors and more critical messages.68+Because we certainly don't want to get a mail for warnings or other69+useless logs that might happen during request handling.70+71+Before you run that in production, please also look at :ref:`log-format`72+to put more information into that error mail. That will save you from a73+lot of frustration.74+75+76+Logging to a File77+-----------------78+79+Even if you get mails, you probably also want to log warnings. It's a80+good idea to keep as much information around that might be required to81+debug a problem. Please note that Flask itself will not issue any82+warnings in the core system, so it's your responsibility to warn in the83+code if something seems odd.84+85+There are a couple of handlers provided by the logging system out of the86+box but not all of them are useful for basic error logging. The most87+interesting are probably the following:88+89+- :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.98+99+Once you picked your log handler, do like you did with the SMTP handler100+above, just make sure to use a lower setting (I would recommend101+`WARNING`)::102+103+ 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)109+110+.. _log-format:111+112+Controlling the Log Format113+--------------------------114+115+By default a handler will only write the message string into a file or116+send you that message as mail. But a log record stores more information117+and it makes a lot of sense to configure your logger to also contain that118+information so that you have a better idea of why that error happened, and119+more importantly, where it did.120+121+A formatter can be instanciated with a format string. Note that122+tracebacks are appended to the log entry automatically. You don't have to123+do that in the log formatter format string.124+125+Here some example setups:126+127+Email128+`````129+130+::131+132+ 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)s139+140+ Message:141+142+ %(message)s143+ '''))144+145+File logging146+````````````147+148+::149+150+ from logging import Formatter151+ file_handler.setFormatter(Formatter(152+ '%(astime)s %(levelname)s: %(message)s '153+ '[in %(pathname)s:%(lineno)d]'154+ ))155+156+157+Complex Log Formatting158+``````````````````````159+160+Here is a list of useful formatting variables for the format string. Note161+that this list is not complete, consult the official documentation of the162+:mod:`logging` package for a full list.163+164++------------------+----------------------------------------------------+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++------------------+----------------------------------------------------+193+194+If you want to further customize the formatting, you can subclass the195+formatter. The formatter has three interesting methods:196+197+: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.208+209+For more information, head over to the official documentation.210+211+212+Other Libraries213+---------------214+215+So far we only configured the logger your application created itself.216+Other libraries might log themselves as well. For example, SQLAlchemy use217+logging heavily in the core. While there is a method to configure all218+loggers at once in the :mod:`logging` package, I would not recommend using219+it. There might be a situation in which you want to have multiple220+separate applications running side by side in the same Python interpreter221+and then it becomes impossible to have different logging setups for those.222+223+Instead, I would recommend figuring out which loggers you are interested224+in, getting the loggers with the :func:`~logging.getLogger` function and225+iterating over them to attach handlers::226+227+ 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 lines531 f= request.files['the_file']532 f.save('/var/www/uploads/' + secure_filename(f.filename))533 ...534 535+For some better examples, checkout the :ref:`uploading-files` pattern.536+537 Cookies538 ```````539 540 To access cookies you can use the :attr:`~flask.request.cookies`99 unmodified lines640 To flash a message use the :func:`~flask.flash` method, to get hold of the641 messages you can use :func:`~flask.get_flashed_messages` which is also642 available in the templates. Check out the :ref:`message-flashing-pattern`643 for a full example.644+645+Logging646+-------647+648+.. versionadded:: 0.5649+650+Sometimes you might be in the situation where you deal with data that651+should be correct, but actually is not. For example you have some client652+side code that sends an HTTP request to the server, and it's obviously653+malformed. This might be caused by a user tempering with the data, or the654+client code failed. Most the time, it's okay to reply with ``400 Bad655+Request`` in that situation, but other times it is not and the code has to656+continue working.657+658+Yet you want to log that something fishy happened. This is where loggers659+come in handy. As of Flask 0.5 a logger is preconfigured for you to use.660+661+Here are some example log calls::662+663+ app.logger.debug('A value for debugging')664+ app.logger.warning('A warning ocurred (%d apples)', 42)665+ app.logger.error('An error occoured')666+667+The attached :attr:`~flask.Flask.logger` is a standard logging668+:class:`~logging.Logger`, so head over to the official stdlib669+documentation for more information.modified:tests/flask_tests.py+22 added
643 unmodified lines644 assert 'Traceback (most recent call last):' in err645 assert '1/0' in err646 assert 'ZeroDivisionError:' in err647 648+ 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'669 670+671 def suite():672 from minitwit_tests import MiniTwitTestCase673 from flaskr_tests import FlaskrTestCase674 suite = unittest.TestSuite()15 unmodified linesmodified:flask.py+15 added-9 removed
664 unmodified lines665 #: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 lines768 @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::774+775+ 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 lines1089 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)1093 1094 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 lines1178 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)1191 1192 def request_context(self, environ):1193 """Creates a request context from the given environment and binds31 unmodified lines