Skip to content
Myr

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

3 files+132 added−10 removed

modified:tests/flask_tests.py+63 added-1 removed
14 unmodified lines
15import sys16import flask17import unittest18import tempfile19from contextlib import contextmanager20from datetime import datetime21from werkzeug import parse_date, parse_options_header22from cStringIO import StringIO23
2 unmodified lines
26sys.path.append(os.path.join(example_path, 'flaskr'))27sys.path.append(os.path.join(example_path, 'minitwit'))282930@contextmanager31def catch_stderr():32 old_stderr = sys.stderr33 sys.stderr = rv = StringIO()34 try:35 yield rv36 finally:37 sys.stderr = old_stderr383940class ContextTestCase(unittest.TestCase):4142 def test_context_binding(self):43 app = flask.Flask(__name__)
551 unmodified lines
595 assert value == 'attachment'596 assert options['filename'] == 'index.txt'597598599class LoggingTestCase(unittest.TestCase):600601 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 ''608609 @app.route('/exc')610 def exc():611 1/0612 c = app.test_client()613614 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 out619620 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'627628 def test_exception_logging(self):629 from logging import StreamHandler630 out = StringIO()631 app = flask.Flask(__name__)632 app.logger.addHandler(StreamHandler(out))633634 @app.route('/')635 def index():636 1/0637638 rv = app.test_client().get('/')639 assert rv.status_code == 500640 assert 'Internal Server Error' in rv.data641642 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 err647648649def 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 lines
modified:CHANGES+4 added
7 unmodified lines
89Release date to be announced1011- 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.1617Version 0.218-----------19
21 unmodified lines
modified:flask.py+65 added-9 removed
19 unmodified lines
20from werkzeug import Request as RequestBase, Response as ResponseBase, \21 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \22 ImmutableDict, cached_property, wrap_file, Headers23from werkzeug.routing import Map, Rule24from werkzeug.exceptions import HTTPException24from werkzeug.exceptions import HTTPException, InternalServerError25from werkzeug.contrib.securecookie import SecureCookie2627# try to load the best simplejson implementation available. If JSON28# is not installed, we add a failing class.
629 unmodified lines
658 #:659 #: .. versionadded:: 0.2660 use_x_sendfile = False661662 #: 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 )673674 #: 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 lines
764 get_flashed_messages=get_flashed_messages765 )766 self.jinja_env.filters['tojson'] = _tojson_filter767768 @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 logger785786 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 to
249 unmodified lines
1039 """Registers a template context processor function."""1040 self.template_context_processors[None].append(f)1041 return f10421043 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.10471048 .. versionadded: 0.51049 """1050 handler = self.error_handlers.get(e.code)1051 if handler is None:1052 return e1053 return handler(e)10541055 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.10611062 .. 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)10741075 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 a
4 unmodified lines
1083 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)10901091 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