From 85c52743f7b99ac6575d87080a9ffb7540acbf18 Mon Sep 17 00:00:00 2001 From: Nick Johnson Date: Mon, 21 Sep 2015 12:20:19 -0700 Subject: [PATCH] Refs #18773 -- Improved template variable exception logging message. --- django/template/base.py | 9 +++++++-- tests/template_tests/test_logging.py | 21 +++++++++++++++------ 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/django/template/base.py b/django/template/base.py index f4d6b0e6b0..52586e7ab5 100644 --- a/django/template/base.py +++ b/django/template/base.py @@ -902,8 +902,13 @@ class Variable(object): else: raise except Exception as e: - template_name = getattr(context, 'template_name', 'unknown') - logger.debug('{} - {}'.format(template_name, e)) + template_name = getattr(context, 'template_name', None) or 'unknown' + logger.debug( + "Exception while resolving variable '%s' in template '%s'.", + bit, + template_name, + exc_info=True, + ) if getattr(e, 'silent_variable_failure', False): current = context.template.engine.string_if_invalid diff --git a/tests/template_tests/test_logging.py b/tests/template_tests/test_logging.py index f6a9bcb672..4b47abd289 100644 --- a/tests/template_tests/test_logging.py +++ b/tests/template_tests/test_logging.py @@ -34,7 +34,7 @@ class VariableResolveLoggingTests(SimpleTestCase): @property def template_name(self): - return "template" + return "template_name" @property def template(self): @@ -51,19 +51,28 @@ class VariableResolveLoggingTests(SimpleTestCase): return self.__dict__[item] Variable('article').resolve(TestObject()) + self.assertEqual( - self.test_handler.log_record.msg, - 'template - Attribute does not exist.' + self.test_handler.log_record.getMessage(), + "Exception while resolving variable 'article' in template 'template_name'." ) + self.assertIsNotNone(self.test_handler.log_record.exc_info) + raised_exception = self.test_handler.log_record.exc_info[1] + self.assertEqual(str(raised_exception), 'Attribute does not exist.') def test_log_on_variable_does_not_exist_not_silent(self): with self.assertRaises(VariableDoesNotExist): Variable('article.author').resolve({'article': {'section': 'News'}}) self.assertEqual( - self.test_handler.log_record.msg, - 'unknown - Failed lookup for key [author] in %r' % - ("{%r: %r}" % ('section', 'News'), ) + self.test_handler.log_record.getMessage(), + "Exception while resolving variable 'author' in template 'unknown'." + ) + self.assertIsNotNone(self.test_handler.log_record.exc_info) + raised_exception = self.test_handler.log_record.exc_info[1] + self.assertEqual( + str(raised_exception), + 'Failed lookup for key [author] in %r' % ("{%r: %r}" % ('section', 'News')) ) def test_no_log_when_variable_exists(self):