simplify logging configuration
Before adoption: this commit came in with the history the project adopted, so no landing records it.
single default handler and formatter don't remove handlers configure level once using setLevel document logging reorganize logging tests
authored by David Lord · committed by David Lord · parent 85fa8aa · 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
Provenance
- Commit
66b1b75- Tree
c8c3e03- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
85fa8aa
13 files changed+397 added−449 removed
modified:docs/config.rst+5 added-15 removed
197 unmodified lines198 :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.199 200 Default: ``timedelta(hours=12)`` (``43200`` seconds)201 202-.. py:data:: LOGGER_NAME203-204- 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__``.206-207- Default: ``None``208-209-.. py:data:: LOGGER_HANDLER_POLICY210-211- 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.214-215- Default: ``'always'``216-202 .. py:data:: SERVER_NAME203 204 Inform the application what host and port it is bound to. Required for205 subdomain route matching support.107 unmodified lines313 .. versionadded:: 0.11314 ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,315 ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``316 317+.. versionchanged:: 1.0318+319+ ``LOGGER_NAME`` and ``LOGGER_HANDLER_POLICY`` were removed. See320+ :ref:`logging` for information about configuration.321+322 Configuring from Files323 ----------------------324 325 Configuration becomes more useful if you can store it in a separate file,263 unmodified linesmodified:docs/contents.rst.inc+1 added
14 unmodified lines15 tutorial/index16 templating17 testing18 errorhandling19+ logging20 config21 signals22 views23 appcontext40 unmodified linesmodified:docs/errorhandling.rst+4 added-206 removed
141 unmodified lines142 143 Handlers are prioritized by specificity of the exception classes they are144 registered for instead of the order they are registered in.145 146-Error Mails147------------146+Logging147+-------148 149-If the application runs in production mode (which it will do on your150-server) you might not see any log messages. The reason for that is that151-Flask by default will just report to the WSGI error stream or stderr152-(depending on what's available). Where this ends up is sometimes hard to153-find. Often it's in your webserver's log files.149+See :ref:`logging` for information on how to log exceptions, such as by150+emailing them to admins.151 155-I can pretty much promise you however that if you only use a logfile for156-the application errors you will never look at it except for debugging an157-issue when a user reported it for you. What you probably want instead is158-a mail the second the exception happened. Then you get an alert and you159-can do something about it.152 161-Flask uses the Python builtin logging system, and it can actually send162-you mails for errors which is probably what you want. Here is how you can163-configure the Flask logger to send you mails for exceptions::164-165- 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)174-175-So what just happened? We created a new176-:class:`~logging.handlers.SMTPHandler` that will send mails with the mail177-server listening on ``127.0.0.1`` to all the `ADMINS` from the address178-*server-error@example.com* with the subject "YourApplication Failed". If179-your mail server requires credentials, these can also be provided. For180-that check out the documentation for the181-:class:`~logging.handlers.SMTPHandler`.182-183-We also tell the handler to only send errors and more critical messages.184-Because we certainly don't want to get a mail for warnings or other185-useless logs that might happen during request handling.186-187-Before you run that in production, please also look at :ref:`logformat` to188-put more information into that error mail. That will save you from a lot189-of frustration.190-191-192-Logging to a File193------------------194-195-Even if you get mails, you probably also want to log warnings. It's a196-good idea to keep as much information around that might be required to197-debug a problem. By default as of Flask 0.11, errors are logged to your198-webserver's log automatically. Warnings however are not. Please note199-that Flask itself will not issue any warnings in the core system, so it's200-your responsibility to warn in the code if something seems odd.201-202-There are a couple of handlers provided by the logging system out of the203-box but not all of them are useful for basic error logging. The most204-interesting are probably the following:205-206-- :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.215-216-Once you picked your log handler, do like you did with the SMTP handler217-above, just make sure to use a lower setting (I would recommend218-`WARNING`)::219-220- 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)226-227-.. _logformat:228-229-Controlling the Log Format230---------------------------231-232-By default a handler will only write the message string into a file or233-send you that message as mail. A log record stores more information,234-and it makes a lot of sense to configure your logger to also contain that235-information so that you have a better idea of why that error happened, and236-more importantly, where it did.237-238-A formatter can be instantiated with a format string. Note that239-tracebacks are appended to the log entry automatically. You don't have to240-do that in the log formatter format string.241-242-Here are some example setups:243-244-Email245-`````246-247-::248-249- 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)s256-257- Message:258-259- %(message)s260- '''))261-262-File logging263-````````````264-265-::266-267- from logging import Formatter268- file_handler.setFormatter(Formatter(269- '%(asctime)s %(levelname)s: %(message)s '270- '[in %(pathname)s:%(lineno)d]'271- ))272-273-274-Complex Log Formatting275-``````````````````````276-277-Here is a list of useful formatting variables for the format string. Note278-that this list is not complete, consult the official documentation of the279-:mod:`logging` package for a full list.280-281-.. tabularcolumns:: |p{3cm}|p{12cm}|282-283-+------------------+----------------------------------------------------+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-+------------------+----------------------------------------------------+313-314-If you want to further customize the formatting, you can subclass the315-formatter. The formatter has three interesting methods:316-317-: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.328-329-For more information, head over to the official documentation.330-331-332-Other Libraries333----------------334-335-So far we only configured the logger your application created itself.336-Other libraries might log themselves as well. For example, SQLAlchemy uses337-logging heavily in its core. While there is a method to configure all338-loggers at once in the :mod:`logging` package, I would not recommend using339-it. There might be a situation in which you want to have multiple340-separate applications running side by side in the same Python interpreter341-and then it becomes impossible to have different logging setups for those.342-343-Instead, I would recommend figuring out which loggers you are interested344-in, getting the loggers with the :func:`~logging.getLogger` function and345-iterating over them to attach handlers::346-347- 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)353-354-153 Debugging Application Errors154 ============================155 156 For production applications, configure your application with logging and59 unmodified linesadded:docs/logging.rst+175 added
1+.. _logging:2+3+Logging4+=======5+6+Flask uses standard Python :mod:`logging`. All Flask-related messages are7+logged 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. ::10+11+ @app.route('/login', methods=['POST'])12+ def login():13+ user = get_user(request.form['username'])14+15+ 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)22+23+24+Basic Configuration25+-------------------26+27+When you want to configure logging for your project, you should do it as soon28+as possible when the program starts. If :meth:`app.logger <flask.Flask.logger>`29+is accessed before logging is configured, it will add a default handler. If30+possible, configure logging before creating the application object.31+32+This example uses :func:`~logging.config.dictConfig` to create a logging33+configuration similar to Flask's default, except for all logs::34+35+ from logging.config import dictConfig36+37+ 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+ })52+53+ app = Flask(__name__)54+55+56+Default Configuration57+`````````````````````58+59+If you do not configure logging yourself, Flask will add a60+:class:`~logging.StreamHandler` to :meth:`app.logger <flask.Flask.logger>`61+automatically. During requests, it will write to the stream specified by the62+WSGI server in ``environ['wsgi.errors']`` (which is usually63+:data:`sys.stderr`). Outside a request, it will log to :data:`sys.stderr`.64+65+66+Removing the Default Handler67+````````````````````````````68+69+If you configured logging after accessing70+:meth:`app.logger <flask.Flask.logger>`, and need to remove the default71+handler, you can import and remove it::72+73+ from flask.logging import default_handler74+75+ app.logger.removeHandler(default_handler)76+77+78+Email Errors to Admins79+----------------------80+81+When running the application on a remote server for production, you probably82+won't be looking at the log messages very often. The WSGI server will probably83+send log messages to a file, and you'll only check that file if a user tells84+you something went wrong.85+86+To be proactive about discovering and fixing bugs, you can configure a87+:class:`logging.handlers.SMTPHandler` to send an email when errors and higher88+are logged. ::89+90+ import logging91+ from logging.handlers import SMTPHandler92+93+ 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+ ))103+104+ if not app.debug:105+ app.logger.addHandler(mail_handler)106+107+This requires that you have an SMTP server set up on the same server. See the108+Python docs for more information about configuring the handler.109+110+111+Injecting Request Information112+-----------------------------113+114+Seeing more information about the request, such as the IP address, may help115+debugging some errors. You can subclass :class:`logging.Formatter` to inject116+your own fields that can be used in messages. You can change the formatter for117+Flask's default handler, the mail handler defined above, or any other118+handler. ::119+120+ from flask import request121+ from flask.logging import default_handler122+123+ class RequestFormatter(logging.Formatter):124+ def format(self, record):125+ record.url = request.url126+ record.remote_addr = request.remote_addr127+ return super().format(record)128+129+ 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)135+136+137+Other Libraries138+---------------139+140+Other libraries may use logging extensively, and you want to see relevant141+messages from those logs too. The simplest way to do this is to add handlers142+to the root logger instead of only the app logger. ::143+144+ from flask.logging import default_handler145+146+ root = logging.getLogger()147+ root.addHandler(default_handler)148+ root.addHandler(mail_handler)149+150+Depending on your project, it may be more useful to configure each logger you151+care about separately, instead of configuring only the root logger. ::152+153+ 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)160+161+162+Werkzeug163+````````164+165+Werkzeug logs basic request/response information to the ``'werkzeug'`` logger.166+If the root logger has no handlers configured, Werkzeug adds a167+:class:`~logging.StreamHandler` to its logger.168+169+170+Flask Extensions171+````````````````172+173+Depending on the situation, an extension may choose to log to174+:meth:`app.logger <flask.Flask.logger>` or its own named logger. Consult each175+extension's documentation for details.modified:flask/app.py+21 added-35 removed
14 unmodified lines15 from functools import update_wrapper16 from itertools import chain17 from threading import Lock18 19-from werkzeug.datastructures import ImmutableDict, Headers20-from werkzeug.exceptions import BadRequest, HTTPException, \21- InternalServerError, MethodNotAllowed, default_exceptions, \22- BadRequestKeyError19+from werkzeug.datastructures import Headers, ImmutableDict20+from werkzeug.exceptions import BadRequest, BadRequestKeyError, HTTPException, \21+ InternalServerError, MethodNotAllowed, default_exceptions22 from werkzeug.routing import BuildError, Map, RequestRedirect, Rule23 24 from . import cli, json25 from ._compat import integer_types, reraise, string_types, text_type2 unmodified lines28 from .globals import _request_ctx_stack, g, request, session29 from .helpers import _PackageBoundObject, \30 _endpoint_from_view_func, find_package, get_debug_flag, \31 get_flashed_messages, locked_cached_property, url_for32+from .logging import create_logger33 from .sessions import SecureCookieSessionInterface34 from .signals import appcontext_tearing_down, got_request_exception, \35 request_finished, request_started, request_tearing_down36 from .templating import DispatchingJinjaLoader, Environment, \37 _default_template_ctx_processor38 from .wrappers import Request, Response39 40-# a lock used for logger initialization41-_logger_lock = Lock()42-40 # a singleton sentinel value for parameter defaults41 _sentinel = object()42 43 216 unmodified lines260 #: 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')263 267- #: 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')272-264 #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.265 #:266 #: .. versionadded:: 0.10267 json_encoder = json.JSONEncoder16 unmodified lines284 '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 lines380 #: exactly like a regular dictionary but supports additional methods381 #: to load a config from files.382 self.config = self.make_config(instance_relative_config)383 395- # Prepare the deferred setup of the logger.396- self._logger = None397- self.logger_name = self.import_name398-384 #: 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 lines597 if rv is not None:598 return rv599 return self.debug600 616- @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`.605 623- 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`.608 609+ If there are no handlers configured, a default handler will be added.610+ See :ref:`logging` for more information.611+612+ .. 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.619+620 .. 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 rv623 624 @locked_cached_property625 def jinja_env(self):626 """The Jinja2 environment used to load templates."""1557 unmodified linesmodified:flask/logging.py+46 added-71 removed
1-# -*- coding: utf-8 -*-2-"""3- flask.logging4- ~~~~~~~~~~~~~5-6- Implements the logging support for Flask.7-8- :copyright: (c) 2015 by Armin Ronacher.9- :license: BSD, see LICENSE for more details.10-"""11-1 from __future__ import absolute_import2 3+import logging4 import sys5 6 from werkzeug.local import LocalProxy17-from logging import getLogger, StreamHandler, Formatter, getLoggerClass, \18- DEBUG, ERROR19-from .globals import _request_ctx_stack7 8+from .globals import request9 22-PROD_LOG_FORMAT = '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'23-DEBUG_LOG_FORMAT = (24- '-' * 80 + '\n' +25- '%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n' +26- '%(message)s\n' +27- '-' * 8028-)10 30-11 @LocalProxy32-def _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.12+def 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``.15+16+ 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.stderr22 23 43-def _should_log_for(app, mode):44- policy = app.config['LOGGER_HANDLER_POLICY']45- if policy == mode or policy == 'always':46- return True47- return False24+def 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 = logger30 31+ while current:32+ if any(handler.level <= level for handler in current.handlers):33+ return True34 50-def 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+ break37 59- 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.parent39 65- 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 False41 70- class ProductionHandler(StreamHandler):71- def emit(self, record):72- if not app.debug and _should_log_for(app, 'production'):73- StreamHandler.emit(self, record)42 75- 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``.45+default_handler = logging.StreamHandler(wsgi_errors_stream)46+default_handler.setFormatter(logging.Formatter(47+ '[%(asctime)s] %(levelname)s in %(module)s: %(message)s'48+))49 79- prod_handler = ProductionHandler(_proxy_stream)80- prod_handler.setLevel(ERROR)81- prod_handler.setFormatter(Formatter(PROD_LOG_FORMAT))50 83- 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)51+def create_logger(app):52+ """Get the ``'flask.app'`` logger and configure it if needed.53 91- # 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.56 57+ 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')62+63+ if app.debug and logger.level == logging.NOTSET:64+ logger.setLevel(logging.DEBUG)65+66+ if not has_level_handler(logger):67+ logger.addHandler(default_handler)68+69 return loggermodified:tests/test_basic.py+28 added-5 removed
736 unmodified lines737 738 739 def test_teardown_request_handler_error(app, client):740 called = []741- app.config['LOGGER_HANDLER_POLICY'] = 'never'741 app.testing = False742 743 @app.teardown_request744 def teardown_request1(exc):67 unmodified lines812 assert called == [1, 2, 3, 4, 5, 6]813 814 815 def test_error_handling(app, client):817- app.config['LOGGER_HANDLER_POLICY'] = 'never'816 app.testing = False817 818 @app.errorhandler(404)819 def not_found(e):37 unmodified lines857 assert 'Use a subclass' in exc_info.value.args[0]858 859 860 def test_error_handling_processing(app, client):863- app.config['LOGGER_HANDLER_POLICY'] = 'never'861 app.testing = False862 863 @app.errorhandler(500)864 def internal_server_error(e):13 unmodified lines878 assert resp.data == b'internal server error'879 880 881 def test_baseexception_error_handling(app, client):885- app.config['LOGGER_HANDLER_POLICY'] = 'never'882 app.testing = False883 884 @app.route('/')885 def broken_func():130 unmodified lines1016 with pytest.raises(NotFound):1017 client.get('/fail')1018 1019 1020+def test_error_handler_after_processor_error(app, client):1021+ app.testing = False1022+1023+ @app.before_request1024+ def before_request():1025+ if trigger == 'before':1026+ 1 // 01027+1028+ @app.after_request1029+ def after_request(response):1030+ if trigger == 'after':1031+ 1 // 01032+ return response1033+1034+ @app.route('/')1035+ def index():1036+ return 'Foo'1037+1038+ @app.errorhandler(500)1039+ def internal_server_error(e):1040+ return 'Hello Server Error', 5001041+1042+ for trigger in 'before', 'after':1043+ rv = client.get('/')1044+ assert rv.status_code == 5001045+ assert rv.data == b'Hello Server Error'1046+1047+1048 def test_enctype_debug_helper(app, client):1049 from flask.debughelpers import DebugFilesKeyError1050 app.debug = True1051 396 unmodified lines1448 1449 1450 def test_exception_propagation(app, client):1451 def apprunner(config_key):1428- app.config['LOGGER_HANDLER_POLICY'] = 'never'1452 1453 @app.route('/')1454 def index():1455 1 // 0399 unmodified linesmodified:tests/test_helpers.py+8 added-96 removed
7 unmodified lines8 :copyright: (c) 2015 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10 """11 12-import pytest13-12+import datetime13 import os14 import uuid16-import datetime15 18-import flask19-from logging import StreamHandler16+import pytest17 from werkzeug.datastructures import Range18 from werkzeug.exceptions import BadRequest, NotFound22-from werkzeug.http import parse_cache_control_header, parse_options_header23-from werkzeug.http import http_date19+from werkzeug.http import http_date, parse_cache_control_header, \20+ parse_options_header21+22+import flask23 from flask._compat import StringIO, text_type25-from flask.helpers import get_debug_flag, make_response24+from flask.helpers import get_debug_flag25 26 27 def has_encoding(name):28 try:629 unmodified lines658 with pytest.raises(BadRequest):659 flask.send_from_directory('static', 'bad\x00')660 661 663-class 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 logger1671-672- def test_debug_log(self, capsys, app, client):673- app.debug = True674-675- @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 ''680-681- @app.route('/exc')682- def exc():683- 1 // 0684-685- 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 err692-693- with pytest.raises(ZeroDivisionError):694- client.get('/exc')695-696- 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 == 10701-702- 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 = False708-709- @app.route('/')710- def index():711- 1 // 0712-713- rv = client.get('/')714- assert rv.status_code == 500715- assert b'Internal Server Error' in rv.data716-717- 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 err722-723- def test_processor_exceptions(self, app, client):724- app.config['LOGGER_HANDLER_POLICY'] = 'never'725- app.testing = False726-727- @app.before_request728- def before_request():729- if trigger == 'before':730- 1 // 0731-732- @app.after_request733- def after_request(response):734- if trigger == 'after':735- 1 // 0736- return response737-738- @app.route('/')739- def index():740- return 'Foo'741-742- @app.errorhandler(500)743- def internal_server_error(e):744- return 'Hello Server Error', 500745-746- for trigger in 'before', 'after':747- rv = client.get('/')748- assert rv.status_code == 500749- assert rv.data == b'Hello Server Error'750-662+class TestUrlFor(object):663 def test_url_for_with_anchor(self, app, req_ctx):664 665 @app.route('/')666 def index():222 unmodified linesadded:tests/test_logging.py+91 added
1+import logging2+import sys3+4+import pytest5+6+from flask._compat import StringIO7+from flask.logging import default_handler, has_level_handler, \8+ wsgi_errors_stream9+10+11+@pytest.fixture(autouse=True)12+def reset_logging(monkeypatch):13+ root_handlers = logging.root.handlers[:]14+ root_level = logging.root.level15+16+ logger = logging.getLogger('flask.app')17+ logger.handlers = []18+ logger.setLevel(logging.NOTSET)19+20+ yield21+22+ logging.root.handlers[:] = root_handlers23+ logging.root.setLevel(root_level)24+25+ logger.handlers = []26+ logger.setLevel(logging.NOTSET)27+28+29+def test_logger(app):30+ assert app.logger.name == 'flask.app'31+ assert app.logger.level == logging.NOTSET32+ assert app.logger.handlers == [default_handler]33+34+35+def test_logger_debug(app):36+ app.debug = True37+ assert app.logger.level == logging.DEBUG38+ assert app.logger.handlers == [default_handler]39+40+41+def test_existing_handler(app):42+ logging.root.addHandler(logging.StreamHandler())43+ assert app.logger.level == logging.NOTSET44+ assert not app.logger.handlers45+46+47+def test_wsgi_errors_stream(app, client):48+ @app.route('/')49+ def index():50+ app.logger.error('test')51+ return ''52+53+ stream = StringIO()54+ client.get('/', errors_stream=stream)55+ assert 'ERROR in test_logging: test' in stream.getvalue()56+57+ assert wsgi_errors_stream._get_current_object() is sys.stderr58+59+ with app.test_request_context(errors_stream=stream):60+ assert wsgi_errors_stream._get_current_object() is stream61+62+63+def test_has_level_handler():64+ logger = logging.getLogger('flask.app')65+ assert not has_level_handler(logger)66+67+ handler = logging.StreamHandler()68+ logging.root.addHandler(handler)69+ assert has_level_handler(logger)70+71+ logger.propagate = False72+ assert not has_level_handler(logger)73+ logger.propagate = True74+75+ handler.setLevel(logging.ERROR)76+ assert not has_level_handler(logger)77+78+79+def test_log_view_exception(app, client):80+ @app.route('/')81+ def index():82+ raise Exception('test')83+84+ 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 errmodified:tests/test_subclassing.py+4 added-8 removed
7 unmodified lines8 9 :copyright: (c) 2015 by Armin Ronacher.10 :license: BSD, see LICENSE for more details.11 """12+13 import flask13-from logging import StreamHandler14 15 from flask._compat import StringIO16 17 3 unmodified lines21 pass22 23 out = StringIO()24 app = SuppressedFlask(__name__)25- app.logger_name = 'flask_tests/test_suppressed_exception_logging'26- app.logger.addHandler(StreamHandler(out))25 26 @app.route('/')27 def index():30- 1 // 028+ raise Exception('test')29 32- 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.data35-36- err = out.getvalue()33+ assert not out.getvalue()37- assert err == ''modified:tests/test_templating.py+8 added-12 removed
397 unmodified lines398 assert app.templates_auto_reload == True399 assert app.jinja_env.auto_reload == True400 401 402-def test_template_loader_debugging(test_apps):402+def test_template_loader_debugging(test_apps, monkeypatch):403 from blueprintapp import app404 405 called = []406 11 unmodified lines418 'the blueprint "frontend"') in text419 assert 'See http://flask.pocoo.org/docs/blueprints/#templates' in text420 421 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+ )426 428- with pytest.raises(TemplateNotFound) as excinfo:429- c.get('/missing')427+ with pytest.raises(TemplateNotFound) as excinfo:428+ c.get('/missing')429 431- 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)431 432 assert len(called) == 1433 434 9 unmodified linesmodified:tests/test_testing.py-1 removed
205 unmodified lines206 assert 'cookies' in str(e.value)207 208 209 def test_test_client_context_binding(app, client):210- app.config['LOGGER_HANDLER_POLICY'] = 'never'210 app.testing = False211 212 @app.route('/')213 def index():123 unmodified linesmodified:CHANGES+6 added
104 unmodified lines105 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`_)115 116 .. _#1421: https://github.com/pallets/flask/issues/1421117 .. _#1489: https://github.com/pallets/flask/pull/1489118 .. _#1621: https://github.com/pallets/flask/pull/1621648 unmodified lines