Skip to content

Commit

Permalink
Excent JSON exception logging ot include filename & line number.
Browse files Browse the repository at this point in the history
  • Loading branch information
Fizzadar committed Oct 8, 2021
1 parent 92a3553 commit 338762c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
22 changes: 18 additions & 4 deletions synapse/logging/_terse_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""
import json
import logging
import traceback

_encoder = json.JSONEncoder(ensure_ascii=False, separators=(",", ":"))

Expand Down Expand Up @@ -49,6 +50,22 @@
}


def _extract_exc_info(record: logging.LogRecord) -> dict:
exc_info = {}

exc_type, exc_value, exc_tb = record.exc_info

if exc_type:
exc_info["exc_type"] = f"{exc_type.__name__}"
exc_info["exc_value"] = f"{exc_value}"

frame_summary = traceback.extract_tb(exc_tb, limit=1)[0]
exc_info["exc_filename"] = frame_summary.filename
exc_info["exc_lineno"] = frame_summary.lineno

return exc_info


class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
event = {
Expand All @@ -66,10 +83,7 @@ def _format(self, record: logging.LogRecord, event: dict) -> str:
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}"
event.update(_extract_exc_info(record))

return _encoder.encode(event)

Expand Down
2 changes: 2 additions & 0 deletions tests/logging/test_terse_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,8 @@ def test_with_exception(self):
"namespace",
"exc_type",
"exc_value",
"exc_filename",
"exc_lineno",
]
self.assertCountEqual(log.keys(), expected_log_keys)
self.assertEqual(log["log"], "Hello there, wally!")
Expand Down

0 comments on commit 338762c

Please sign in to comment.