Skip to content

Commit

Permalink
Include exception in json logging (matrix-org#11028)
Browse files Browse the repository at this point in the history
  • Loading branch information
Fizzadar committed Oct 8, 2021
1 parent fea5128 commit 5d3c76d
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog.d/11028.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Include exception information in JSON logging output. Contributed by @Fizzadar at Beeper.
6 changes: 6 additions & 0 deletions synapse/logging/_terse_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ def _format(self, record: logging.LogRecord, event: dict) -> str:
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)


Expand Down
28 changes: 28 additions & 0 deletions tests/logging/test_terse_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,31 @@ def test_with_request_context(self):
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!")

0 comments on commit 5d3c76d

Please sign in to comment.