Skip to content
Myr

Merge pull request #2436 from davidism/logging

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

Simplify logging

authored by David Lord · committed by GitHub · parents 85fa8aa, 66b1b75 · Browse files · 13 files+397 added−449 removed
This commit

State

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

Diff stats

13 files+397 added−449 removed

  • tests:+139 added−122 removed
  • other:+258 added−327 removed

13 files+397 added−449 removed

modified:docs/config.rst+5 added-15 removed
197 unmodified lines
198 :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.199200 Default: ``timedelta(hours=12)`` (``43200`` seconds)201202.. py:data:: LOGGER_NAME203204 The name of the logger that the Flask application sets up. If not set,205 it will take the import name passed to ``Flask.__init__``.206207 Default: ``None``208209.. py:data:: LOGGER_HANDLER_POLICY210211 When to activate the application's logger handler. ``'always'`` always212 enables it, ``'debug'`` only activates it in debug mode, ``'production'``213 only activates it when not in debug mode, and ``'never'`` never enables it.214215 Default: ``'always'``216202.. py:data:: SERVER_NAME203204 Inform the application what host and port it is bound to. Required for205 subdomain route matching support.
107 unmodified lines
313.. versionadded:: 0.11314 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,315 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``316317.. versionchanged:: 1.0318319 ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See320 :ref:`logging` for information about configuration.321322Configuring from Files323----------------------324325Configuration becomes more useful if you can store it in a separate file,
263 unmodified lines
modified:docs/contents.rst.inc+1 added
14 unmodified lines
15 tutorial/index16 templating17 testing18 errorhandling19 logging20 config21 signals22 views23 appcontext
40 unmodified lines
modified:docs/errorhandling.rst+4 added-206 removed
141 unmodified lines
142143 Handlers are prioritized by specificity of the exception classes they are144 registered for instead of the order they are registered in.145146Error Mails147-----------146Logging147-------148149If the application runs in production mode (which it will do on your150server) you might not see any log messages. The reason for that is that151Flask by default will just report to the WSGI error stream or stderr152(depending on what's available). Where this ends up is sometimes hard to153find. Often it's in your webserver's log files.149See :ref:`logging` for information on how to log exceptions, such as by150emailing them to admins.151155I can pretty much promise you however that if you only use a logfile for156the application errors you will never look at it except for debugging an157issue when a user reported it for you. What you probably want instead is158a mail the second the exception happened. Then you get an alert and you159can do something about it.152161Flask uses the Python builtin logging system, and it can actually send162you mails for errors which is probably what you want. Here is how you can163configure the Flask logger to send you mails for exceptions::164165 ADMINS = ['yourname@example.com']166 if not app.debug:167 import logging168 from logging.handlers import SMTPHandler169 mail_handler = SMTPHandler('127.0.0.1',170 'server-error@example.com',171 ADMINS, 'YourApplication Failed')172 mail_handler.setLevel(logging.ERROR)173 app.logger.addHandler(mail_handler)174175So what just happened? We created a new176:class:`~logging.handlers.SMTPHandler` that will send mails with the mail177server listening on ``127.0.0.1`` to all the `ADMINS` from the address178*server-error@example.com* with the subject "YourApplication Failed". If179your mail server requires credentials, these can also be provided. For180that check out the documentation for the181:class:`~logging.handlers.SMTPHandler`.182183We also tell the handler to only send errors and more critical messages.184Because we certainly don't want to get a mail for warnings or other185useless logs that might happen during request handling.186187Before you run that in production, please also look at :ref:`logformat` to188put more information into that error mail. That will save you from a lot189of frustration.190191192Logging to a File193-----------------194195Even if you get mails, you probably also want to log warnings. It's a196good idea to keep as much information around that might be required to197debug a problem. By default as of Flask 0.11, errors are logged to your198webserver's log automatically. Warnings however are not. Please note199that Flask itself will not issue any warnings in the core system, so it's200your responsibility to warn in the code if something seems odd.201202There are a couple of handlers provided by the logging system out of the203box but not all of them are useful for basic error logging. The most204interesting are probably the following:205206- :class:`~logging.FileHandler` - logs messages to a file on the207 filesystem.208- :class:`~logging.handlers.RotatingFileHandler` - logs messages to a file209 on the filesystem and will rotate after a certain number of messages.210- :class:`~logging.handlers.NTEventLogHandler` - will log to the system211 event log of a Windows system. If you are deploying on a Windows box,212 this is what you want to use.213- :class:`~logging.handlers.SysLogHandler` - sends logs to a UNIX214 syslog.215216Once you picked your log handler, do like you did with the SMTP handler217above, just make sure to use a lower setting (I would recommend218`WARNING`)::219220 if not app.debug:221 import logging222 from themodule import TheHandlerYouWant223 file_handler = TheHandlerYouWant(...)224 file_handler.setLevel(logging.WARNING)225 app.logger.addHandler(file_handler)226227.. _logformat:228229Controlling the Log Format230--------------------------231232By default a handler will only write the message string into a file or233send you that message as mail. A log record stores more information,234and it makes a lot of sense to configure your logger to also contain that235information so that you have a better idea of why that error happened, and236more importantly, where it did.237238A formatter can be instantiated with a format string. Note that239tracebacks are appended to the log entry automatically. You don't have to240do that in the log formatter format string.241242Here are some example setups:243244Email245`````246247::248249 from logging import Formatter250 mail_handler.setFormatter(Formatter('''251 Message type: %(levelname)s252 Location: %(pathname)s:%(lineno)d253 Module: %(module)s254 Function: %(funcName)s255 Time: %(asctime)s256257 Message:258259 %(message)s260 '''))261262File logging263````````````264265::266267 from logging import Formatter268 file_handler.setFormatter(Formatter(269 '%(asctime)s %(levelname)s: %(message)s '270 '[in %(pathname)s:%(lineno)d]'271 ))272273274Complex Log Formatting275``````````````````````276277Here is a list of useful formatting variables for the format string. Note278that this list is not complete, consult the official documentation of the279:mod:`logging` package for a full list.280281.. tabularcolumns:: |p{3cm}|p{12cm}|282283+------------------+----------------------------------------------------+284| Format | Description |285+==================+====================================================+286| ``%(levelname)s``| Text logging level for the message |287| | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``, |288| | ``'ERROR'``, ``'CRITICAL'``). |289+------------------+----------------------------------------------------+290| ``%(pathname)s`` | Full pathname of the source file where the |291| | logging call was issued (if available). |292+------------------+----------------------------------------------------+293| ``%(filename)s`` | Filename portion of pathname. |294+------------------+----------------------------------------------------+295| ``%(module)s`` | Module (name portion of filename). |296+------------------+----------------------------------------------------+297| ``%(funcName)s`` | Name of function containing the logging call. |298+------------------+----------------------------------------------------+299| ``%(lineno)d`` | Source line number where the logging call was |300| | issued (if available). |301+------------------+----------------------------------------------------+302| ``%(asctime)s`` | Human-readable time when the |303| | :class:`~logging.LogRecord` was created. |304| | By default this is of the form |305| | ``"2003-07-08 16:49:45,896"`` (the numbers after |306| | the comma are millisecond portion of the time). |307| | This can be changed by subclassing the formatter |308| | and overriding the |309| | :meth:`~logging.Formatter.formatTime` method. |310+------------------+----------------------------------------------------+311| ``%(message)s`` | The logged message, computed as ``msg % args`` |312+------------------+----------------------------------------------------+313314If you want to further customize the formatting, you can subclass the315formatter. The formatter has three interesting methods:316317:meth:`~logging.Formatter.format`:318 handles the actual formatting. It is passed a319 :class:`~logging.LogRecord` object and has to return the formatted320 string.321:meth:`~logging.Formatter.formatTime`:322 called for `asctime` formatting. If you want a different time format323 you can override this method.324:meth:`~logging.Formatter.formatException`325 called for exception formatting. It is passed an :attr:`~sys.exc_info`326 tuple and has to return a string. The default is usually fine, you327 don't have to override it.328329For more information, head over to the official documentation.330331332Other Libraries333---------------334335So far we only configured the logger your application created itself.336Other libraries might log themselves as well. For example, SQLAlchemy uses337logging heavily in its core. While there is a method to configure all338loggers at once in the :mod:`logging` package, I would not recommend using339it. There might be a situation in which you want to have multiple340separate applications running side by side in the same Python interpreter341and then it becomes impossible to have different logging setups for those.342343Instead, I would recommend figuring out which loggers you are interested344in, getting the loggers with the :func:`~logging.getLogger` function and345iterating over them to attach handlers::346347 from logging import getLogger348 loggers = [app.logger, getLogger('sqlalchemy'),349 getLogger('otherlibrary')]350 for logger in loggers:351 logger.addHandler(mail_handler)352 logger.addHandler(file_handler)353354153Debugging Application Errors154============================155156For production applications, configure your application with logging and
59 unmodified lines
added:docs/logging.rst+175 added
1.. _logging:23Logging4=======56Flask uses standard Python :mod:`logging`. All Flask-related messages are7logged under the ``'flask'`` logger namespace.8:meth:`Flask.logger <flask.Flask.logger>` returns the logger named9``'flask.app'``, and can be used to log messages for your application. ::1011 @app.route('/login', methods=['POST'])12 def login():13 user = get_user(request.form['username'])1415 if user.check_password(request.form['password']):16 login_user(user)17 app.logger.info('%s logged in successfully', user.username)18 return redirect(url_for('index'))19 else:20 app.logger.info('%s failed to log in', user.username)21 abort(401)222324Basic Configuration25-------------------2627When you want to configure logging for your project, you should do it as soon28as possible when the program starts. If :meth:`app.logger <flask.Flask.logger>`29is accessed before logging is configured, it will add a default handler. If30possible, configure logging before creating the application object.3132This example uses :func:`~logging.config.dictConfig` to create a logging33configuration similar to Flask's default, except for all logs::3435 from logging.config import dictConfig3637 dictConfig({38 'version': 1,39 'formatters': {'default': {40 'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',41 }},42 'handlers': {'wsgi': {43 'class': 'logging.StreamHandler',44 'stream': 'ext://flask.logging.wsgi_errors_stream',45 'formatter': 'default'46 }},47 'root': {48 'level': 'INFO',49 'handlers': ['wsgi']50 }51 })5253 app = Flask(__name__)545556Default Configuration57`````````````````````5859If you do not configure logging yourself, Flask will add a60:class:`~logging.StreamHandler` to :meth:`app.logger <flask.Flask.logger>`61automatically. During requests, it will write to the stream specified by the62WSGI server in ``environ['wsgi.errors']`` (which is usually63:data:`sys.stderr`). Outside a request, it will log to :data:`sys.stderr`.646566Removing the Default Handler67````````````````````````````6869If you configured logging after accessing70:meth:`app.logger <flask.Flask.logger>`, and need to remove the default71handler, you can import and remove it::7273 from flask.logging import default_handler7475 app.logger.removeHandler(default_handler)767778Email Errors to Admins79----------------------8081When running the application on a remote server for production, you probably82won't be looking at the log messages very often. The WSGI server will probably83send log messages to a file, and you'll only check that file if a user tells84you something went wrong.8586To be proactive about discovering and fixing bugs, you can configure a87:class:`logging.handlers.SMTPHandler` to send an email when errors and higher88are logged. ::8990 import logging91 from logging.handlers import SMTPHandler9293 mail_handler = SMTPHandler(94 mailhost='127.0.0.1',95 fromaddr='server-error@example.com',96 toaddrs=['admin@example.com'],97 subject='Application Error'98 )99 mail_handler.setLevel(logging.ERROR)100 mail_handler.setFormatter(logging.Formatter(101 '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'102 ))103104 if not app.debug:105 app.logger.addHandler(mail_handler)106107This requires that you have an SMTP server set up on the same server. See the108Python docs for more information about configuring the handler.109110111Injecting Request Information112-----------------------------113114Seeing more information about the request, such as the IP address, may help115debugging some errors. You can subclass :class:`logging.Formatter` to inject116your own fields that can be used in messages. You can change the formatter for117Flask's default handler, the mail handler defined above, or any other118handler. ::119120 from flask import request121 from flask.logging import default_handler122123 class RequestFormatter(logging.Formatter):124 def format(self, record):125 record.url = request.url126 record.remote_addr = request.remote_addr127 return super().format(record)128129 formatter = RequestFormatter(130 '[%(asctime)s] %(remote_addr)s requested %(url)s\n'131 '%(levelname)s in %(module)s: %(message)s'132 ))133 default_handler.setFormatter(formatter)134 mail_handler.setFormatter(formatter)135136137Other Libraries138---------------139140Other libraries may use logging extensively, and you want to see relevant141messages from those logs too. The simplest way to do this is to add handlers142to the root logger instead of only the app logger. ::143144 from flask.logging import default_handler145146 root = logging.getLogger()147 root.addHandler(default_handler)148 root.addHandler(mail_handler)149150Depending on your project, it may be more useful to configure each logger you151care about separately, instead of configuring only the root logger. ::152153 for logger in (154 app.logger,155 logging.getLogger('sqlalchemy'),156 logging.getLogger('other_package'),157 ):158 logger.addHandler(default_handler)159 logger.addHandler(mail_handler)160161162Werkzeug163````````164165Werkzeug logs basic request/response information to the ``'werkzeug'`` logger.166If the root logger has no handlers configured, Werkzeug adds a167:class:`~logging.StreamHandler` to its logger.168169170Flask Extensions171````````````````172173Depending on the situation, an extension may choose to log to174:meth:`app.logger <flask.Flask.logger>` or its own named logger. Consult each175extension's documentation for details.
modified:flask/app.py+21 added-35 removed
14 unmodified lines
15from functools import update_wrapper16from itertools import chain17from threading import Lock1819from werkzeug.datastructures import ImmutableDict, Headers20from werkzeug.exceptions import BadRequest, HTTPException, \21 InternalServerError, MethodNotAllowed, default_exceptions, \22 BadRequestKeyError19from werkzeug.datastructures import Headers, ImmutableDict20from werkzeug.exceptions import BadRequest, BadRequestKeyError, HTTPException, \21 InternalServerError, MethodNotAllowed, default_exceptions22from werkzeug.routing import BuildError, Map, RequestRedirect, Rule2324from . import cli, json25from ._compat import integer_types, reraise, string_types, text_type
2 unmodified lines
28from .globals import _request_ctx_stack, g, request, session29from .helpers import _PackageBoundObject, \30 _endpoint_from_view_func, find_package, get_debug_flag, \31 get_flashed_messages, locked_cached_property, url_for32from .logging import create_logger33from .sessions import SecureCookieSessionInterface34from .signals import appcontext_tearing_down, got_request_exception, \35 request_finished, request_started, request_tearing_down36from .templating import DispatchingJinjaLoader, Environment, \37 _default_template_ctx_processor38from .wrappers import Request, Response3940# a lock used for logger initialization41_logger_lock = Lock()4240# a singleton sentinel value for parameter defaults41_sentinel = object()4243
216 unmodified lines
260 #: This attribute can also be configured from the config with the261 #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.262 use_x_sendfile = ConfigAttribute('USE_X_SENDFILE')263267 #: The name of the logger to use. By default the logger name is the268 #: package name passed to the constructor.269 #:270 #: .. versionadded:: 0.4271 logger_name = ConfigAttribute('LOGGER_NAME')272264 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.265 #:266 #: .. versionadded:: 0.10267 json_encoder = json.JSONEncoder
16 unmodified lines
284 'PRESERVE_CONTEXT_ON_EXCEPTION': None,285 'SECRET_KEY': None,286 'PERMANENT_SESSION_LIFETIME': timedelta(days=31),287 'USE_X_SENDFILE': False,297 'LOGGER_NAME': None,298 'LOGGER_HANDLER_POLICY': 'always',288 'SERVER_NAME': None,289 'APPLICATION_ROOT': '/',290 'SESSION_COOKIE_NAME': 'session',291 'SESSION_COOKIE_DOMAIN': None,
88 unmodified lines
380 #: exactly like a regular dictionary but supports additional methods381 #: to load a config from files.382 self.config = self.make_config(instance_relative_config)383395 # Prepare the deferred setup of the logger.396 self._logger = None397 self.logger_name = self.import_name398384 #: A dictionary of all view functions registered. The keys will385 #: be function names which are also used to generate URLs and386 #: the values are the function objects themselves.387 #: To register a view function, use the :meth:`route` decorator.
209 unmodified lines
597 if rv is not None:598 return rv599 return self.debug600616 @property601 @locked_cached_property602 def logger(self):618 """A :class:`logging.Logger` object for this application. The619 default configuration is to log to stderr if the application is620 in debug mode. This logger can be used to (surprise) log messages.621 Here some examples::603 """The ``'flask.app'`` logger, a standard Python604 :class:`~logging.Logger`.605623 app.logger.debug('A value for debugging')624 app.logger.warning('A warning occurred (%d apples)', 42)625 app.logger.error('An error occurred')606 In debug mode, the logger's :attr:`~logging.Logger.level` will be set607 to :data:`~logging.DEBUG`.608609 If there are no handlers configured, a default handler will be added.610 See :ref:`logging` for more information.611612 .. versionchanged:: 1.0613 Behavior was simplified. The logger is always named614 ``flask.app``. The level is only set during configuration, it615 doesn't check ``app.debug`` each time. Only one format is used,616 not different ones depending on ``app.debug``. No handlers are617 removed, and a handler is only added if no handlers are already618 configured.619620 .. versionadded:: 0.3621 """629 if self._logger and self._logger.name == self.logger_name:630 return self._logger631 with _logger_lock:632 if self._logger and self._logger.name == self.logger_name:633 return self._logger634 from flask.logging import create_logger635 self._logger = rv = create_logger(self)622 return create_logger(self)636 return rv623624 @locked_cached_property625 def jinja_env(self):626 """The Jinja2 environment used to load templates."""
1557 unmodified lines
modified:flask/logging.py+46 added-71 removed
1# -*- coding: utf-8 -*-2"""3 flask.logging4 ~~~~~~~~~~~~~56 Implements the logging support for Flask.78 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111from __future__ import absolute_import23import logging4import sys56from werkzeug.local import LocalProxy17from logging import getLogger, StreamHandler, Formatter, getLoggerClass, \18 DEBUG, ERROR19from .globals import _request_ctx_stack78from .globals import request922PROD_LOG_FORMAT = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'23DEBUG_LOG_FORMAT = (24 '-' * 80 + '\n' +25 '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +26 '%(message)s\n' +27 '-' * 8028)103011@LocalProxy32def _proxy_stream():33 """Finds the most appropriate error stream for the application. If a34 WSGI request is in flight we log to wsgi.errors, otherwise this resolves35 to sys.stderr.12def wsgi_errors_stream():13 """Find the most appropriate error stream for the application. If a request14 is active, log to ``wsgi.errors``, otherwise use ``sys.stderr``.1516 If you configure your own :class:`logging.StreamHandler`, you may want to17 use this for the stream. If you are using file or dict configuration and18 can't import this directly, you can refer to it as19 ``ext://flask.logging.wsgi_errors_stream``.20 """37 ctx = _request_ctx_stack.top38 if ctx is not None:39 return ctx.request.environ['wsgi.errors']40 return sys.stderr21 return request.environ['wsgi.errors'] if request else sys.stderr222343def _should_log_for(app, mode):44 policy = app.config['LOGGER_HANDLER_POLICY']45 if policy == mode or policy == 'always':46 return True47 return False24def has_level_handler(logger):25 """Check if there is a handler in the logging chain that will handle the26 given logger's :meth:`effective level <~logging.Logger.getEffectiveLevel>`.27 """28 level = logger.getEffectiveLevel()29 current = logger3031 while current:32 if any(handler.level <= level for handler in current.handlers):33 return True3450def create_logger(app):51 """Creates a logger for the given application. This logger works52 similar to a regular Python logger but changes the effective logging53 level based on the application's debug flag. Furthermore this54 function also removes all attached handlers in case there was a55 logger with the log name before.56 """57 Logger = getLoggerClass()35 if not current.propagate:36 break3759 class DebugLogger(Logger):60 def getEffectiveLevel(self):61 if self.level == 0 and app.debug:62 return DEBUG63 return Logger.getEffectiveLevel(self)38 current = current.parent3965 class DebugHandler(StreamHandler):66 def emit(self, record):67 if app.debug and _should_log_for(app, 'debug'):68 StreamHandler.emit(self, record)40 return False4170 class ProductionHandler(StreamHandler):71 def emit(self, record):72 if not app.debug and _should_log_for(app, 'production'):73 StreamHandler.emit(self, record)4275 debug_handler = DebugHandler()76 debug_handler.setLevel(DEBUG)77 debug_handler.setFormatter(Formatter(DEBUG_LOG_FORMAT))43#: Log messages to :func:`~flask.logging.wsgi_errors_stream` with the format44#: ``[%(asctime)s] %(levelname)s in %(module)s: %(message)s``.45default_handler = logging.StreamHandler(wsgi_errors_stream)46default_handler.setFormatter(logging.Formatter(47 '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'48))4979 prod_handler = ProductionHandler(_proxy_stream)80 prod_handler.setLevel(ERROR)81 prod_handler.setFormatter(Formatter(PROD_LOG_FORMAT))5083 logger = getLogger(app.logger_name)84 # just in case that was not a new logger, get rid of all the handlers85 # already attached to it.86 del logger.handlers[:]87 logger.__class__ = DebugLogger88 logger.addHandler(debug_handler)89 logger.addHandler(prod_handler)51def create_logger(app):52 """Get the ``'flask.app'`` logger and configure it if needed.5391 # Disable propagation by default92 logger.propagate = False54 When :attr:`~flask.Flask.debug` is enabled, set the logger level to55 :data:`logging.DEBUG` if it is not set.5657 If there is no handler for the logger's effective level, add a58 :class:`~logging.StreamHandler` for59 :func:`~flask.logging.wsgi_errors_stream` with a basic format.60 """61 logger = logging.getLogger('flask.app')6263 if app.debug and logger.level == logging.NOTSET:64 logger.setLevel(logging.DEBUG)6566 if not has_level_handler(logger):67 logger.addHandler(default_handler)6869 return logger
modified:tests/test_basic.py+28 added-5 removed
736 unmodified lines
737738739def test_teardown_request_handler_error(app, client):740 called = []741 app.config['LOGGER_HANDLER_POLICY'] = 'never'741 app.testing = False742743 @app.teardown_request744 def teardown_request1(exc):
67 unmodified lines
812 assert called == [1, 2, 3, 4, 5, 6]813814815def test_error_handling(app, client):817 app.config['LOGGER_HANDLER_POLICY'] = 'never'816 app.testing = False817818 @app.errorhandler(404)819 def not_found(e):
37 unmodified lines
857 assert 'Use a subclass' in exc_info.value.args[0]858859860def test_error_handling_processing(app, client):863 app.config['LOGGER_HANDLER_POLICY'] = 'never'861 app.testing = False862863 @app.errorhandler(500)864 def internal_server_error(e):
13 unmodified lines
878 assert resp.data == b'internal server error'879880881def test_baseexception_error_handling(app, client):885 app.config['LOGGER_HANDLER_POLICY'] = 'never'882 app.testing = False883884 @app.route('/')885 def broken_func():
130 unmodified lines
1016 with pytest.raises(NotFound):1017 client.get('/fail')101810191020def test_error_handler_after_processor_error(app, client):1021 app.testing = False10221023 @app.before_request1024 def before_request():1025 if trigger == 'before':1026 1 // 010271028 @app.after_request1029 def after_request(response):1030 if trigger == 'after':1031 1 // 01032 return response10331034 @app.route('/')1035 def index():1036 return 'Foo'10371038 @app.errorhandler(500)1039 def internal_server_error(e):1040 return 'Hello Server Error', 50010411042 for trigger in 'before', 'after':1043 rv = client.get('/')1044 assert rv.status_code == 5001045 assert rv.data == b'Hello Server Error'104610471048def test_enctype_debug_helper(app, client):1049 from flask.debughelpers import DebugFilesKeyError1050 app.debug = True1051
396 unmodified lines
144814491450def test_exception_propagation(app, client):1451 def apprunner(config_key):1428 app.config['LOGGER_HANDLER_POLICY'] = 'never'14521453 @app.route('/')1454 def index():1455 1 // 0
399 unmodified lines
modified:tests/test_helpers.py+8 added-96 removed
7 unmodified lines
8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""1112import pytest1312import datetime13import os14import uuid16import datetime1518import flask19from logging import StreamHandler16import pytest17from werkzeug.datastructures import Range18from werkzeug.exceptions import BadRequest, NotFound22from werkzeug.http import parse_cache_control_header, parse_options_header23from werkzeug.http import http_date19from werkzeug.http import http_date, parse_cache_control_header, \20 parse_options_header2122import flask23from flask._compat import StringIO, text_type25from flask.helpers import get_debug_flag, make_response24from flask.helpers import get_debug_flag252627def has_encoding(name):28 try:
629 unmodified lines
658 with pytest.raises(BadRequest):659 flask.send_from_directory('static', 'bad\x00')660661663class TestLogging(object):664 def test_logger_cache(self):665 app = flask.Flask(__name__)666 logger1 = app.logger667 assert app.logger is logger1668 assert logger1.name == __name__669 app.logger_name = __name__ + '/test_logger_cache'670 assert app.logger is not logger1671672 def test_debug_log(self, capsys, app, client):673 app.debug = True674675 @app.route('/')676 def index():677 app.logger.warning('the standard library is dead')678 app.logger.debug('this is a debug statement')679 return ''680681 @app.route('/exc')682 def exc():683 1 // 0684685 with client:686 client.get('/')687 out, err = capsys.readouterr()688 assert 'WARNING in test_helpers [' in err689 assert os.path.basename(__file__.rsplit('.', 1)[0] + '.py') in err690 assert 'the standard library is dead' in err691 assert 'this is a debug statement' in err692693 with pytest.raises(ZeroDivisionError):694 client.get('/exc')695696 def test_debug_log_override(self, app):697 app.debug = True698 app.logger_name = 'flask_tests/test_debug_log_override'699 app.logger.level = 10700 assert app.logger.level == 10701702 def test_exception_logging(self, app, client):703 out = StringIO()704 app.config['LOGGER_HANDLER_POLICY'] = 'never'705 app.logger_name = 'flask_tests/test_exception_logging'706 app.logger.addHandler(StreamHandler(out))707 app.testing = False708709 @app.route('/')710 def index():711 1 // 0712713 rv = client.get('/')714 assert rv.status_code == 500715 assert b'Internal Server Error' in rv.data716717 err = out.getvalue()718 assert 'Exception on / [GET]' in err719 assert 'Traceback (most recent call last):' in err720 assert '1 // 0' in err721 assert 'ZeroDivisionError:' in err722723 def test_processor_exceptions(self, app, client):724 app.config['LOGGER_HANDLER_POLICY'] = 'never'725 app.testing = False726727 @app.before_request728 def before_request():729 if trigger == 'before':730 1 // 0731732 @app.after_request733 def after_request(response):734 if trigger == 'after':735 1 // 0736 return response737738 @app.route('/')739 def index():740 return 'Foo'741742 @app.errorhandler(500)743 def internal_server_error(e):744 return 'Hello Server Error', 500745746 for trigger in 'before', 'after':747 rv = client.get('/')748 assert rv.status_code == 500749 assert rv.data == b'Hello Server Error'750662class TestUrlFor(object):663 def test_url_for_with_anchor(self, app, req_ctx):664665 @app.route('/')666 def index():
222 unmodified lines
added:tests/test_logging.py+91 added
1import logging2import sys34import pytest56from flask._compat import StringIO7from flask.logging import default_handler, has_level_handler, \8 wsgi_errors_stream91011@pytest.fixture(autouse=True)12def reset_logging(monkeypatch):13 root_handlers = logging.root.handlers[:]14 root_level = logging.root.level1516 logger = logging.getLogger('flask.app')17 logger.handlers = []18 logger.setLevel(logging.NOTSET)1920 yield2122 logging.root.handlers[:] = root_handlers23 logging.root.setLevel(root_level)2425 logger.handlers = []26 logger.setLevel(logging.NOTSET)272829def test_logger(app):30 assert app.logger.name == 'flask.app'31 assert app.logger.level == logging.NOTSET32 assert app.logger.handlers == [default_handler]333435def test_logger_debug(app):36 app.debug = True37 assert app.logger.level == logging.DEBUG38 assert app.logger.handlers == [default_handler]394041def test_existing_handler(app):42 logging.root.addHandler(logging.StreamHandler())43 assert app.logger.level == logging.NOTSET44 assert not app.logger.handlers454647def test_wsgi_errors_stream(app, client):48 @app.route('/')49 def index():50 app.logger.error('test')51 return ''5253 stream = StringIO()54 client.get('/', errors_stream=stream)55 assert 'ERROR in test_logging: test' in stream.getvalue()5657 assert wsgi_errors_stream._get_current_object() is sys.stderr5859 with app.test_request_context(errors_stream=stream):60 assert wsgi_errors_stream._get_current_object() is stream616263def test_has_level_handler():64 logger = logging.getLogger('flask.app')65 assert not has_level_handler(logger)6667 handler = logging.StreamHandler()68 logging.root.addHandler(handler)69 assert has_level_handler(logger)7071 logger.propagate = False72 assert not has_level_handler(logger)73 logger.propagate = True7475 handler.setLevel(logging.ERROR)76 assert not has_level_handler(logger)777879def test_log_view_exception(app, client):80 @app.route('/')81 def index():82 raise Exception('test')8384 app.testing = False85 stream = StringIO()86 rv = client.get('/', errors_stream=stream)87 assert rv.status_code == 50088 assert rv.data89 err = stream.getvalue()90 assert 'Exception on / [GET]' in err91 assert 'Exception: test' in err
modified:tests/test_subclassing.py+4 added-8 removed
7 unmodified lines
89 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11"""1213import flask13from logging import StreamHandler1415from flask._compat import StringIO1617
3 unmodified lines
21 pass2223 out = StringIO()24 app = SuppressedFlask(__name__)25 app.logger_name = 'flask_tests/test_suppressed_exception_logging'26 app.logger.addHandler(StreamHandler(out))2526 @app.route('/')27 def index():30 1 // 028 raise Exception('test')2932 rv = app.test_client().get('/')30 rv = app.test_client().get('/', errors_stream=out)31 assert rv.status_code == 50032 assert b'Internal Server Error' in rv.data3536 err = out.getvalue()33 assert not out.getvalue()37 assert err == ''
modified:tests/test_templating.py+8 added-12 removed
397 unmodified lines
398 assert app.templates_auto_reload == True399 assert app.jinja_env.auto_reload == True400401402def test_template_loader_debugging(test_apps):402def test_template_loader_debugging(test_apps, monkeypatch):403 from blueprintapp import app404405 called = []406
11 unmodified lines
418 'the blueprint "frontend"') in text419 assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text420421 with app.test_client() as c:422 try:423 old_load_setting = app.config['EXPLAIN_TEMPLATE_LOADING']424 old_handlers = app.logger.handlers[:]425 app.logger.handlers = [_TestHandler()]426 app.config['EXPLAIN_TEMPLATE_LOADING'] = True422 monkeypatch.setitem(app.config, 'EXPLAIN_TEMPLATE_LOADING', True)423 monkeypatch.setattr(424 logging.getLogger('flask'), 'handlers', [_TestHandler()]425 )426428 with pytest.raises(TemplateNotFound) as excinfo:429 c.get('/missing')427 with pytest.raises(TemplateNotFound) as excinfo:428 c.get('/missing')429431 assert 'missing_template.html' in str(excinfo.value)432 finally:433 app.logger.handlers[:] = old_handlers434 app.config['EXPLAIN_TEMPLATE_LOADING'] = old_load_setting430 assert 'missing_template.html' in str(excinfo.value)431432 assert len(called) == 1433434
9 unmodified lines
modified:tests/test_testing.py-1 removed
205 unmodified lines
206 assert 'cookies' in str(e.value)207208209def test_test_client_context_binding(app, client):210 app.config['LOGGER_HANDLER_POLICY'] = 'never'210 app.testing = False211212 @app.route('/')213 def index():
123 unmodified lines
modified:CHANGES+6 added
104 unmodified lines
105 from ``.env`` and ``.flaskenv`` files if python-dotenv is installed.106 (`#2416`_)107- When passing a full URL to the test client, use the scheme in the URL instead108 of the ``PREFERRED_URL_SCHEME``. (`#2436`_)109- ``app.logger`` has been simplified. ``LOGGER_NAME`` and110 ``LOGGER_HANDLER_POLICY`` config was removed. The logger is always named111 ``flask.app``. The level is only set on first access, it doesn't check112 ``app.debug`` each time. Only one format is used, not different ones113 depending on ``app.debug``. No handlers are removed, and a handler is only114 added if no handlers are already configured. (`#2436`_)115116.. _#1421: https://github.com/pallets/flask/issues/1421117.. _#1489: https://github.com/pallets/flask/pull/1489118.. _#1621: https://github.com/pallets/flask/pull/1621
648 unmodified lines