Include exception in json logging (#11028)

This commit is contained in:
Nick Barrett 2021-10-08 12:08:25 +01:00 committed by GitHub
parent 0b4d5ce5e3
commit bb228f3523
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 0 deletions

View file

@ -0,0 +1 @@
Include exception information in JSON logging output. Contributed by @Fizzadar at Beeper.

View file

@ -65,6 +65,12 @@ class JsonFormatter(logging.Formatter):
if key not in _IGNORED_LOG_RECORD_ATTRIBUTES:
event[key] = value
if record.exc_info:
exc_type, exc_value, _ = record.exc_info
if exc_type:
event["exc_type"] = f"{exc_type.__name__}"
event["exc_value"] = f"{exc_value}"
return _encoder.encode(event)

View file

@ -198,3 +198,31 @@ class TerseJsonTestCase(LoggerCleanupMixin, TestCase):
self.assertEqual(log["url"], "/_matrix/client/versions")
self.assertEqual(log["protocol"], "1.1")
self.assertEqual(log["user_agent"], "")
def test_with_exception(self):
"""
The logging exception type & value should be added to the JSON response.
"""
handler = logging.StreamHandler(self.output)
handler.setFormatter(JsonFormatter())
logger = self.get_logger(handler)
try:
raise ValueError("That's wrong, you wally!")
except ValueError:
logger.exception("Hello there, %s!", "wally")
log = self.get_log_line()
# The terse logger should give us these keys.
expected_log_keys = [
"log",
"level",
"namespace",
"exc_type",
"exc_value",
]
self.assertCountEqual(log.keys(), expected_log_keys)
self.assertEqual(log["log"], "Hello there, wally!")
self.assertEqual(log["exc_type"], "ValueError")
self.assertEqual(log["exc_value"], "That's wrong, you wally!")