8000 Fixed #24526 -- Combined django.request/security loggers with the roo… · ddriddle/django@8efea1b · GitHub
[go: up one dir, main page]

Skip to content

Commit 8efea1b

Browse files
committed
Fixed #24526 -- Combined django.request/security loggers with the root logger.
Thanks Carl Meyer for review.
1 parent 3768236 commit 8efea1b

File tree

8 files changed

+75
-49
lines changed

8 files changed

+75
-49
lines changed

django/test/utils.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -616,3 +616,18 @@ def override_script_prefix(prefix):
616616
Decorator or context manager to temporary override the script prefix.
617617
"""
618618
return ScriptPrefix(prefix)
619+
620+
621+
class LoggingCaptureMixin(object):
622+
"""
623+
Capture the output from the 'django' logger and store it on the class's
624+
logger_output attribute.
625+
"""
626+
def setUp(self):
627+
self.logger = logging.getLogger('django')
628+
self.old_stream = self.logger.handlers[0].stream
629+
self.logger_output = six.StringIO()
630+
self.logger.handlers[0].stream = self.logger_output
631+
632+
def tearDown(self):
633+
self.logger.handlers[0].stream = self.old_stream

django/utils/log.py

Lines changed: 1 addition & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,17 +40,7 @@
4040
},
4141
'loggers': {
4242
'django': {
43-
'handlers': ['console'],
44-
},
45-
'django.request': {
46-
'handlers': ['mail_admins'],
47-
'level': 'ERROR',
48-
'propagate': False,
49-
},
50-
'django.security': {
51-
'handlers': ['mail_admins'],
52-
'level': 'ERROR',
53-
'propagate': False,
43+
'handlers': ['console', 'mail_admins'],
5444
},
5545
'py.warnings': {
5646
'handlers': ['console'],

docs/releases/1.9.txt

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -358,6 +358,26 @@ template object. These classes have been combined into
358358
:class:`~django.template.base.Origin` and is now always set regardless of the
359359
engine debug setting.
360360

361+
.. _default-logging-changes-19:
362+
363+
Changes to the default logging configuration
364+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
365+
366+
To make it easier to write custom logging configurations, Django's default
367+
logging configuration no longer defines 'django.request' and 'django.security'
368+
loggers. Instead, it defines a single 'django' logger with two handlers:
369+
370+
* 'console': filtered at the ``INFO`` level and only active if ``DEBUG=True``.
371+
* 'mail_admins': filtered at the ``ERROR`` level and only active if
372+
``DEBUG=False``.
373+
374+
If you aren't overriding Django's default logging, you should see minimal
375+
changes in behavior, but you might see some new logging to the ``runserver``
376+
console, for example.
377+
378+
If you are overriding Django's default logging, you should check to see how
379+
your configuration merges with the new defaults.
380+
361381
Miscellaneous
362382
~~~~~~~~~~~~~
363383

docs/topics/logging.txt

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -266,12 +266,12 @@ If you use this example, be sure to change the ``'filename'`` path to a
266266
location that's writable by the user that's running the Django application.
267267

268268
Second, here's an example of how to make the logging system print Django's
269-
logging to the console. It overrides the fact that ``django.request`` and
270-
``django.security`` don't propagate their log entries by default. It may be
271-
useful during local development.
269+
logging to the console. It may be useful during local development.
272270

273271
By default, this config only sends messages of level ``INFO`` or higher to the
274-
console. Django does not log many such messages. Set the environment variable
272+
console (same as Django's default logging config, except that the default only
273+
displays log records when ``DEBUG=True``). Django does not log many such
274+
messages. With this config, however, you can also set the environment variable
275275
``DJANGO_LOG_LEVEL=DEBUG`` to see all of Django's debug logging which is very
276276
verbose as it includes all database queries::
277277

@@ -293,6 +293,11 @@ verbose as it includes all database queries::
293293
},
294294
}
295295

296+
.. versionchanged:: 1.9
297+
298+
Django's default logging configuration changed. See :ref:`the release notes
299+
<default-logging-changes-19>` for a description of the changes.
300+
296301
Finally, here's an example of a fairly complex logging setup::
297302

298303
LOGGING = {
@@ -525,14 +530,12 @@ a client that does not match :setting:`ALLOWED_HOSTS`, Django will return a 400
525530
response, and an error message will be logged to the
526531
``django.security.DisallowedHost`` logger.
527532

528-
Only the parent ``django.security`` logger is configured by default, and all
529-
child loggers will propagate to the parent logger. The ``django.security``
530-
logger is configured the same as the ``django.request`` logger, and any error
531-
events will be mailed to admins. Requests resulting in a 400 response due to
532-
a ``SuspiciousOperation`` will not be logged to the ``django.request`` logger,
533-
but only to the ``django.security`` logger.
533+
These log events will reach the 'django' logger by default, which mails error
534+
events to admins when ``DEBUG=False``. Requests resulting in a 400 response due
535+
to a ``SuspiciousOperation`` will not be logged to the ``django.request``
536+
logger, but only to the ``django.security`` logger.
534537

535-
To silence a particular type of SuspiciousOperation, you can override that
538+
To silence a particular type of ``SuspiciousOperation``, you can override that
536539
specific logger following this example:
537540

538541
.. code-block:: python
@@ -704,20 +707,20 @@ By default, Django configures the following logging:
704707
When :setting:`DEBUG` is ``True``:
705708

706709
* The ``django`` catch-all logger sends all messages at the ``INFO`` level or
707-
higher to the console. Django doesn't make any such logging calls at this
708-
time (all logging is at the ``DEBUG`` level or handled by the
709-
``django.request`` and ``django.security`` loggers).
710+
higher to the console.
710711

711712
* The ``py.warnings`` logger, which handles messages from ``warnings.warn()``,
712713
sends messages to the console.
713714

714715
When :setting:`DEBUG` is ``False``:
715716

716-
* The ``django.request`` and ``django.security`` loggers send messages with
717-
``ERROR`` or ``CRITICAL`` level to :class:`AdminEmailHandler`. These loggers
718-
ignore anything at the ``WARNING`` level or below and log entries aren't
719-
propagated to other loggers (they won't reach the ``django`` catch-all
720-
logger, even when ``DEBUG`` is ``True``).
717+
* The ``django`` logger send messages with ``ERROR`` or ``CRITICAL`` level to
718+
:class:`AdminEmailHandler`.
719+
720+
.. versionchanged:: 1.9
721+
722+
Django's default logging configuration changed. See :ref:`the release notes
723+
<default-logging-changes-19>` for a description of the changes.
721724

722725
See also :ref:`Configuring logging <configuring-logging>` to learn how you can
723726
complement or replace this default logging configuration.

tests/logging_tests/tests.py

Lines changed: 6 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from django.core import mail
1010
from django.core.files.temp import NamedTemporaryFile
1111
from django.test import RequestFactory, TestCase, override_settings
12-
from django.test.utils import patch_logger
12+
from django.test.utils import LoggingCaptureMixin, patch_logger
1313
from django.utils.deprecation import RemovedInNextVersionWarning
1414
from django.utils.encoding import force_text
1515
from django.utils.log import (
@@ -65,26 +65,18 @@ def test_require_debug_true_filter(self):
6565
self.assertEqual(filter_.filter("record is not used"), False)
6666

6767

68-
class DefaultLoggingTest(TestCase):
69-
def setUp(self):
70-
self.logger = logging.getLogger('django')
71-
self.old_stream = self.logger.handlers[0].stream
72-
73-
def tearDown(self):
74-
self.logger.handlers[0].stream = self.old_stream
68+
class DefaultLoggingTest(LoggingCaptureMixin, TestCase):
7569

7670
def test_django_logger(self):
7771
"""
7872
The 'django' base logger only output anything when DEBUG=True.
7973
"""
80-
output = StringIO()
81-
self.logger.handlers[0].stream = output
8274
self.logger.error("Hey, this is an error.")
83-
self.assertEqual(output.getvalue(), '')
75+
self.assertEqual(self.logger_output.getvalue(), '')
8476

8577
with self.settings(DEBUG=True):
8678
self.logger.error("Hey, this is an error.")
87-
self.assertEqual(output.getvalue(), 'Hey, this is an error.\n')
79+
self.assertEqual(self.logger_output.getvalue(), 'Hey, this is an erro F987 r.\n')
8880

8981

9082
class WarningLoggerTests(TestCase):
@@ -167,11 +159,10 @@ def _callback(record):
167159

168160

169161
class AdminEmailHandlerTest(TestCase):
170-
logger = logging.getLogger('django.request')
162+
logger = logging.getLogger('django')
171163

172164
def get_admin_email_handler(self, logger):
173-
# Inspired from views/views.py: send_log()
174-
# ensuring the AdminEmailHandler does not get filtered out
165+
# Ensure that AdminEmailHandler does not get filtered out
175166
# even with DEBUG=True.
176167
admin_email_handler = [
177168
h for h in logger.handlers

tests/runtests.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
from django.utils.deprecation import (
2020
RemovedInDjango20Warning, RemovedInDjango21Warning,
2121
)
22+
from django.utils.log import DEFAULT_LOGGING
2223

2324
warnings.simplefilter("error", RemovedInDjango20Warning)
2425
warnings.simplefilter("error", RemovedInDjango21Warning)
@@ -144,6 +145,11 @@ def no_available_apps(self):
144145
'auth': 'django.contrib.auth.tests.migrations',
145146
'contenttypes': 'contenttypes_tests.migrations',
146147
}
148+
log_config = DEFAULT_LOGGING
149+
# Filter out non-error logging so we don't have to capture it in lots of
150+
# tests.
151+
log_config['loggers']['django']['level'] = 'ERROR'
152+
settings.LOGGING = log_config
147153

148154
if verbosity > 0:
149155
# Ensure any warnings captured to logging are piped through a verbose

tests/view_tests/tests/test_debug.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change< F438 /th>
@@ -16,6 +16,7 @@
1616
from django.core.urlresolvers import reverse
1717
from django.template.base import TemplateDoesNotExist
1818
from django.test import RequestFactory, TestCase, override_settings
19+
from django.test.utils import LoggingCaptureMixin
1920
from django.utils import six
2021
from django.utils.encoding import force_bytes, force_text
2122
from django.utils.functional import SimpleLazyObject
@@ -48,7 +49,7 @@ def __call__(self):
4849

4950

5051
@override_settings(DEBUG=True, ROOT_URLCONF="view_tests.urls")
51-
class DebugViewTests(TestCase):
52+
class DebugViewTests(LoggingCaptureMixin, TestCase):
5253

5354
def test_files(self):
5455
response = self.client.get('/raises/')
@@ -642,7 +643,7 @@ def verify_paranoid_email(self, view):
642643

643644

644645
@override_settings(ROOT_URLCONF='view_tests.urls')
645-
class ExceptionReporterFilterTests(TestCase, ExceptionReportTestMixin):
646+
class ExceptionReporterFilterTests(ExceptionReportTestMixin, LoggingCaptureMixin, TestCase):
646647
"""
647648
Ensure that sensitive information can be filtered out of error reports.
648649
Refs #14614.
@@ -833,7 +834,7 @@ def test_settings_with_sensitive_keys(self):
833834
self.assertNotContains(response, 'should not be displayed', status_code=500)
834835

835836

836-
class AjaxResponseExceptionReporterFilter(TestCase, ExceptionReportTestMixin):
837+
class AjaxResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptureMixin, TestCase):
837838
"""
838839
Ensure that sensitive information can be filtered out of error reports.
839840

tests/view_tests/views.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def render_no_template(request):
102102

103103

104104
def send_log(request, exc_info):
105-
logger = logging.getLogger('django.request')
105+
logger = logging.getLogger('django')
106106
# The default logging config has a logging filter to ensure admin emails are
107107
# only sent with DEBUG=False, but since someone might choose to remove that
108108
# filter, we still want to be able to test the behavior of error emails

0 commit comments

Comments
 (0)
0