Skip to content

Commit

Permalink
Improved exception logging in Coba to now print exception __cause__ i…
Browse files Browse the repository at this point in the history
…f it exists.
  • Loading branch information
mrucker committed Aug 17, 2023
1 parent ebc92e2 commit 5002d4c
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
20 changes: 17 additions & 3 deletions coba/context/loggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,20 @@ def filter(self, log: Union[str,Exception]) -> str:
elif isinstance(log, CobaException):
return f"EXCEPTION: {log}"
else:
tb = ''.join(traceback.format_tb(log.__traceback__))
msg = ''.join(traceback.TracebackException.from_exception(log).format_exception_only())
return f"Unexpected exception:\n\n{tb}\n {msg}"
return f'Unexpected exception:\n\n{self.format_exception(log)}'

def format_exception(self, ex: Exception):

out = []

if ex.__cause__ is not None:
out.append(self.format_exception(ex.__cause__))
out.append("The above exception was the direct cause of the following exception:\n")

tb = ''.join(traceback.format_tb(ex.__traceback__))
msg = ''.join(traceback.TracebackException.from_exception(ex).format_exception_only())

if tb : out.append(tb)
if msg: out.append(f' {msg}')

return '\n'.join(out)
24 changes: 22 additions & 2 deletions coba/tests/test_context_loggers.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,10 +603,9 @@ def test_filter_exception(self):

log = decorator.filter(exception)

tb = ''.join(traceback.format_tb(exception.__traceback__))
msg = ''.join(traceback.TracebackException.from_exception(exception).format_exception_only())

expected_log = f"Unexpected exception:\n\n{tb}\n {msg}"
expected_log = f"Unexpected exception:\n\n {msg}"

self.assertEqual(log, expected_log)

Expand All @@ -627,6 +626,27 @@ def test_filter_exception_raise(self):

self.assertEqual(log, expected_log)

def test_filter_exception_raise_with_caues(self):

decorator = ExceptLog()
outer_ex = Exception("Out Exception")
inner_ex = Exception("In Exception")

try:
raise inner_ex from outer_ex
except Exception as ex:
log = decorator.filter(ex)

tb = ''.join(traceback.format_tb(ex.__traceback__))
msg = ''.join(traceback.TracebackException.from_exception(ex).format_exception_only())

expected_log = (
'Unexpected exception:\n\n Exception: Out Exception\n\nThe above exception '
f'was the direct cause of the following exception:\n\n{tb}\n {msg}'
)

self.assertEqual(log, expected_log)

def test_filter_coba_exception(self):

decorator = ExceptLog()
Expand Down

0 comments on commit 5002d4c

Please sign in to comment.