Fixed after_request handlers being called twice in some cases and improved logging system
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 bc00fd1 · Browse files · 3 files·+51 added−24 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+51 added−24 removed
- tests:+12 added−4 removed
- other:+39 added−20 removed
Provenance
- Commit
9983e84- Tree
29ae8bb- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
bc00fd1
3 files changed+51 added−24 removed
modified:tests/flask_tests.py+12 added-4 removed
286 unmodified lines287 assert 'Internal Server Error' in rv.data288 assert len(called) == 1289 290 def test_after_request_handler_error(self):291- error_out = StringIO()291+ called = []292 app = flask.Flask(__name__)293- app.logger.addHandler(StreamHandler(error_out))293 @app.after_request294 def after_request(response):295+ called.append(True)296 1/0297 return response298 @app.route('/')299 def fails():300 1/0301 rv = app.test_client().get('/')302 assert rv.status_code == 500303 assert 'Internal Server Error' in rv.data304- assert 'after_request handler failed' in error_out.getvalue()304+ assert len(called) == 1305 306 def test_error_handling(self):307 app = flask.Flask(__name__)308 @app.errorhandler(404)397 unmodified lines706 707 708 class LoggingTestCase(unittest.TestCase):709 710+ def test_logger_cache(self):711+ app = flask.Flask(__name__)712+ logger1 = app.logger713+ assert app.logger is logger1714+ assert logger1.name == __name__715+ app.logger_name = __name__ + '/test_logger_cache'716+ assert app.logger is not logger1717+718 def test_debug_log(self):719 app = flask.Flask(__name__)720 app.debug = True721 @app.route('/')21 unmodified lines743 else:744 assert False, 'debug log ate the exception'745 746 def test_exception_logging(self):739- from logging import StreamHandler747 out = StringIO()748 app = flask.Flask(__name__)749+ app.logger_name = 'flask_tests/test_exception_logging'750 app.logger.addHandler(StreamHandler(out))751 752 @app.route('/')753 def index():102 unmodified linesmodified:CHANGES+2 added
14 unmodified lines15 kicks in.16 - test client has not the ability to preserve the request context17 for a little longer. This can also be used to trigger custom18 requests that do not pop the request stack for testing.19+- because the Python standard library caches loggers, the name of20+ the logger is configurable now to better support unittests.21 22 Version 0.3.123 -------------24 48 unmodified linesmodified:flask.py+37 added-20 removed
14 unmodified lines15 import mimetypes16 from datetime import datetime, timedelta17 18 from itertools import chain19+from threading import Lock20 from jinja2 import Environment, PackageLoader, FileSystemLoader21 from werkzeug import Request as RequestBase, Response as ResponseBase, \22 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \23 ImmutableDict, cached_property, wrap_file, Headers, \26 unmodified lines50 pkg_resources.resource_stream51 except (ImportError, AttributeError):52 pkg_resources = None53 54+# a lock used for logger initialization55+_logger_lock = Lock()56 57+58 class Request(RequestBase):59 """The request object used by default in flask. Remembers the60 matched endpoint and view arguments.61 780 unmodified lines842 #: This attribute can also be configured from the config with the843 #: `USE_X_SENDFILE` configuration key. Defaults to `False`.844 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')845 846+ #: the name of the logger to use. By default the logger name is the847+ #: package name passed to the constructor.848+ #:849+ #: .. versionadded:: 0.4850+ logger_name = ConfigAttribute('LOGGER_NAME')851+852 #: the logging format used for the debug logger. This is only used when853 #: the application is in debug mode, otherwise the attached logging854 #: handler does the formatting.855 #:16 unmodified lines872 'DEBUG': False,873 'SECRET_KEY': None,874 'SESSION_COOKIE_NAME': 'session',875 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),866- 'USE_X_SENDFILE': False876+ 'USE_X_SENDFILE': False,877+ 'LOGGER_NAME': None878 })879 880 def __init__(self, import_name):881 _PackageBoundObject.__init__(self, import_name)2 unmodified lines884 #: exactly like a regular dictionary but supports additional methods885 #: to load a config from files.886 self.config = Config(self.root_path, self.default_config)887 888+ #: prepare the deferred setup of the logger889+ self._logger = None890+ self.logger_name = self.import_name891+892 #: a dictionary of all view functions registered. The keys will893 #: be function names which are also used to generate URLs and894 #: the values are the function objects themselves.895 #: to register a view function, use the :meth:`route` decorator.70 unmodified lines966 get_flashed_messages=get_flashed_messages967 )968 self.jinja_env.filters['tojson'] = _tojson_filter969 955- @cached_property970+ @property971 def logger(self):972 """A :class:`logging.Logger` object for this application. The973 default configuration is to log to stderr if the application is974 in debug mode. This logger can be used to (surprise) log messages.4 unmodified lines979 app.logger.error('An error occoured')980 981 .. versionadded:: 0.3982 """983+ if self._logger and self._logger.name == self.logger_name:984+ return self._logger985+ with _logger_lock:986+ if self._logger and self._logger.name == self.logger_name:987+ return self._logger968- from logging import getLogger, StreamHandler, Formatter, DEBUG969- class DebugHandler(StreamHandler):970- def emit(x, record):971- if self.debug:972- StreamHandler.emit(x, record)973- handler = DebugHandler()974- handler.setLevel(DEBUG)975- handler.setFormatter(Formatter(self.debug_log_format))976- logger = getLogger(self.import_name)977- logger.addHandler(handler)978- return logger988+ from logging import getLogger, StreamHandler, Formatter, DEBUG989+ class DebugHandler(StreamHandler):990+ def emit(x, record):991+ if self.debug:992+ StreamHandler.emit(x, record)993+ handler = DebugHandler()994+ handler.setLevel(DEBUG)995+ handler.setFormatter(Formatter(self.debug_log_format))996+ logger = getLogger(self.logger_name)997+ logger.addHandler(handler)998+ self._logger = logger999+ return logger1000 1001 def create_jinja_loader(self):1002 """Creates the Jinja loader. By default just a package loader for1003 the configured package is returned that looks up templates in the428 unmodified lines1432 rv = self.preprocess_request()1433 if rv is None:1434 rv = self.dispatch_request()1435 response = self.make_response(rv)1436+ except Exception, e:1437+ response = self.make_response(self.handle_exception(e))1438+ try:1439 response = self.process_response(response)1440 except Exception, e:1441 response = self.make_response(self.handle_exception(e))1418- try:1419- response = self.process_response(response)1420- except Exception, e:1421- self.logger.exception('after_request handler failed '1422- 'to postprocess error response. '1423- 'Depending on uncertain state?')1424-1442 return response(environ, start_response)1443 1444 def request_context(self, environ):1445 """Creates a request context from the given environment and binds55 unmodified lines