Added logging support.
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 8c26bec · Browse files · 3 files·+132 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
3 files+132 added−10 removed
- tests:+63 added−1 removed
- other:+69 added−9 removed
Provenance
- Commit
e7f67e1- Tree
a3d209a- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
8c26bec
3 files changed+132 added−10 removed
modified:tests/flask_tests.py+63 added-1 removed
14 unmodified lines15 import sys16 import flask17 import unittest18 import tempfile19+from contextlib import contextmanager20 from datetime import datetime21 from werkzeug import parse_date, parse_options_header22 from cStringIO import StringIO23 2 unmodified lines26 sys.path.append(os.path.join(example_path, 'flaskr'))27 sys.path.append(os.path.join(example_path, 'minitwit'))28 29 30+@contextmanager31+def catch_stderr():32+ old_stderr = sys.stderr33+ sys.stderr = rv = StringIO()34+ try:35+ yield rv36+ finally:37+ sys.stderr = old_stderr38+39+40 class ContextTestCase(unittest.TestCase):41 42 def test_context_binding(self):43 app = flask.Flask(__name__)551 unmodified lines595 assert value == 'attachment'596 assert options['filename'] == 'index.txt'597 598 599+class LoggingTestCase(unittest.TestCase):600+601+ def test_debug_log(self):602+ app = flask.Flask(__name__)603+ app.debug = True604+ @app.route('/')605+ def index():606+ app.logger.warning('the standard library is dead')607+ return ''608+609+ @app.route('/exc')610+ def exc():611+ 1/0612+ c = app.test_client()613+614+ with catch_stderr() as err:615+ rv = c.get('/')616+ out = err.getvalue()617+ assert 'WARNING in flask_tests, flask_tests.py' in out618+ assert 'the standard library is dead' in out619+620+ with catch_stderr() as err:621+ try:622+ c.get('/exc')623+ except ZeroDivisionError:624+ pass625+ else:626+ assert False, 'debug log ate the exception'627+628+ def test_exception_logging(self):629+ from logging import StreamHandler630+ out = StringIO()631+ app = flask.Flask(__name__)632+ app.logger.addHandler(StreamHandler(out))633+634+ @app.route('/')635+ def index():636+ 1/0637+638+ rv = app.test_client().get('/')639+ assert rv.status_code == 500640+ assert 'Internal Server Error' in rv.data641+642+ err = out.getvalue()643+ assert 'Exception on / [GET]' in err644+ assert 'Traceback (most recent call last):' in err645+ assert '1/0' in err646+ assert 'ZeroDivisionError:' in err647+648+649 def suite():650 from minitwit_tests import MiniTwitTestCase651 from flaskr_tests import FlaskrTestCase652 suite = unittest.TestSuite()653 suite.addTest(unittest.makeSuite(ContextTestCase))654 suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))655 suite.addTest(unittest.makeSuite(TemplatingTestCase))595- suite.addTest(unittest.makeSuite(SendfileTestCase))656 suite.addTest(unittest.makeSuite(ModuleTestCase))657+ suite.addTest(unittest.makeSuite(SendfileTestCase))658+ suite.addTest(unittest.makeSuite(LoggingTestCase))659 if flask.json_available:660 suite.addTest(unittest.makeSuite(JSONTestCase))661 suite.addTest(unittest.makeSuite(MiniTwitTestCase))662 suite.addTest(unittest.makeSuite(FlaskrTestCase))5 unmodified linesmodified:CHANGES+4 added
7 unmodified lines8 9 Release date to be announced10 11 - added support for categories for flashed messages.12+- the application now configures a :class:`logging.Handler` and will13+ log request handling exceptions to that logger when not in debug14+ mode. This makes it possible to receive mails on server errors15+ for example.16 17 Version 0.218 -----------19 21 unmodified linesmodified:flask.py+65 added-9 removed
19 unmodified lines20 from werkzeug import Request as RequestBase, Response as ResponseBase, \21 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \22 ImmutableDict, cached_property, wrap_file, Headers23 from werkzeug.routing import Map, Rule24-from werkzeug.exceptions import HTTPException24+from werkzeug.exceptions import HTTPException, InternalServerError25 from werkzeug.contrib.securecookie import SecureCookie26 27 # try to load the best simplejson implementation available. If JSON28 # is not installed, we add a failing class.629 unmodified lines658 #:659 #: .. versionadded:: 0.2660 use_x_sendfile = False661 662+ #: the logging format used for the debug logger. This is only used when663+ #: the application is in debug mode, otherwise the attached logging664+ #: handler does the formatting.665+ #:666+ #: .. versionadded:: 0.5667+ debug_log_format = (668+ '-' * 80 + '\n' +669+ '%(levelname)s in %(module)s, %(filename)s:%(lineno)d]:\n' +670+ '%(message)s\n' +671+ '-' * 80672+ )673+674 #: options that are passed directly to the Jinja2 environment675 jinja_options = ImmutableDict(676 autoescape=True,677 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']86 unmodified lines764 get_flashed_messages=get_flashed_messages765 )766 self.jinja_env.filters['tojson'] = _tojson_filter767 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.773+ """774+ from logging import getLogger, StreamHandler, Formatter, DEBUG775+ class DebugHandler(StreamHandler):776+ def emit(x, record):777+ if self.debug:778+ StreamHandler.emit(x, record)779+ handler = DebugHandler()780+ handler.setLevel(DEBUG)781+ handler.setFormatter(Formatter(self.debug_log_format))782+ logger = getLogger(self.import_name)783+ logger.addHandler(handler)784+ return logger785+786 def create_jinja_loader(self):787 """Creates the Jinja loader. By default just a package loader for788 the configured package is returned that looks up templates in the789 `templates` folder. To add other loaders it's possible to249 unmodified lines1039 """Registers a template context processor function."""1040 self.template_context_processors[None].append(f)1041 return f1042 1043+ def handle_http_exception(self, e):1044+ """Handles an HTTP exception. By default this will invoke the1045+ registered error handlers and fall back to returning the1046+ exception as response.1047+1048+ .. versionadded: 0.51049+ """1050+ handler = self.error_handlers.get(e.code)1051+ if handler is None:1052+ return e1053+ return handler(e)1054+1055+ def handle_exception(self, e):1056+ """Default exception handling that kicks in when an exception1057+ occours that is not catched. In debug mode the exception will1058+ be re-raised immediately, otherwise it is logged an the handler1059+ for an 500 internal server error is used. If no such handler1060+ exists, a default 500 internal server error message is displayed.1061+1062+ .. versionadded: 0.51063+ """1064+ handler = self.error_handlers.get(500)1065+ if self.debug:1066+ raise1067+ self.logger.exception('Exception on %s [%s]' % (1068+ request.path,1069+ request.method1070+ ))1071+ if handler is None:1072+ return InternalServerError()1073+ return handler(e)1074+1075 def dispatch_request(self):1076 """Does the request dispatching. Matches the URL and returns the1077 return value of the view or error handler. This does not have to1078 be a response object. In order to convert the return value to a4 unmodified lines1083 if req.routing_exception is not None:1084 raise req.routing_exception1085 return self.view_functions[req.endpoint](**req.view_args)1086 except HTTPException, e:1025- handler = self.error_handlers.get(e.code)1026- if handler is None:1027- return e1028- return handler(e)1087+ return self.handle_http_exception(e)1088 except Exception, e:1030- handler = self.error_handlers.get(500)1031- if self.debug or handler is None:1032- raise1033- return handler(e)1089+ return self.handle_exception(e)1090 1091 def make_response(self, rv):1092 """Converts the return value from a view function to a real1093 response object that is an instance of :attr:`response_class`.125 unmodified lines