Skip to content

Commit 8bd0839

Browse files
committed
Change exception logging: log exception class name in case of ignore
1 parent 10f16bf commit 8bd0839

File tree

8 files changed

+36
-33
lines changed

8 files changed

+36
-33
lines changed

README.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ Argumented usage with arguments from signature:
8585
max_indent=20, # forwarded to the pretty_repr
8686
spec=None, # use target callable function for spec
8787
blacklisted_names=None, # list argument names, which should be dropped from log
88-
blacklisted_exceptions=None, # Exceptions to skip in log
88+
blacklisted_exceptions=None, # Exceptions to skip details in log (no traceback, no exception details - just class name)
8989
log_call_args=True, # Log call arguments before call
9090
log_call_args_on_exc=True, # Log call arguments if exception happens
9191
log_traceback = True, # Log traceback if exception happens

doc/source/logwrap.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ API: Decorators: `LogWrap` class and `logwrap` function.
3737
:type blacklisted_names: typing.Optional[typing.Iterable[str]]
3838
:param blacklisted_exceptions: list of exception,
3939
which should be re-raised without
40-
producing log record.
40+
producing traceback and text log record.
4141
:type blacklisted_exceptions: typing.Optional[typing.Iterable[typing.Type[Exception]]]
4242
:param log_call_args: log call arguments before executing wrapped function.
4343
:type log_call_args: bool

logwrap/log_wrap.pxd

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,4 @@ cdef:
5050
str _get_func_args_repr(self, sig: inspect.Signature, tuple args, dict kwargs)
5151
void _make_done_record(self, str func_name, result: typing.Any) except *
5252
void _make_calling_record(self, str name, str arguments, str method=?) except *
53-
void _make_exc_record(self, str name, str arguments) except *
53+
void _make_exc_record(self, str name, str arguments, Exception exception) except *

logwrap/log_wrap.py

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,8 @@ def __init__(
188188
:type spec: typing.Optional[typing.Callable]
189189
:param blacklisted_names: Blacklisted argument names. Arguments with this names will be skipped in log.
190190
:type blacklisted_names: typing.Optional[typing.Iterable[str]]
191-
:param blacklisted_exceptions: list of exception, which should be re-raised without producing log record.
191+
:param blacklisted_exceptions: list of exception, which should be re-raised
192+
without producing traceback and text log record.
192193
:type blacklisted_exceptions: typing.Optional[typing.Iterable[typing.Type[Exception]]]
193194
:param log_call_args: log call arguments before executing wrapped function.
194195
:type log_call_args: bool
@@ -297,7 +298,7 @@ def blacklisted_names(self) -> typing.List[str]:
297298

298299
@property
299300
def blacklisted_exceptions(self) -> typing.List[typing.Type[Exception]]:
300-
"""List of exceptions to re-raise without log.
301+
"""List of exceptions to re-raise without log traceback and text.
301302
302303
:rtype: typing.List[typing.Type[Exception]]
303304
"""
@@ -535,11 +536,12 @@ def _make_calling_record(self, name: str, arguments: str, method: str = "Calling
535536
"""
536537
self._logger.log(level=self.log_level, msg=f"{method}: \n{name}({arguments if self.log_call_args else ''})")
537538

538-
def _make_exc_record(self, name: str, arguments: str) -> None:
539+
def _make_exc_record(self, name: str, arguments: str, exception: Exception) -> None:
539540
"""Make log record if exception raised.
540541
541542
:type name: str
542543
:type arguments: str
544+
:type exception: Exception
543545
"""
544546
exc_info = sys.exc_info()
545547
stack: traceback.StackSummary = traceback.extract_stack()
@@ -548,15 +550,13 @@ def _make_exc_record(self, name: str, arguments: str) -> None:
548550
# Make standard traceback string
549551
tb_text: str = (
550552
f"Traceback (most recent call last):\n{''.join(traceback.format_list(full_tb))}{''.join(exc_line)}"
553+
if self.log_traceback and not isinstance(exception, tuple(self.blacklisted_exceptions))
554+
else exception.__class__.__name__
551555
)
552556

553557
self._logger.log(
554558
level=self.exc_level,
555-
msg=(
556-
f"Failed: \n"
557-
f"{name}({arguments if self.log_call_args_on_exc else ''})\n"
558-
f"{tb_text if self.log_traceback else ''}"
559-
),
559+
msg=f"Failed: \n{name}({arguments if self.log_call_args_on_exc else ''})\n{tb_text}",
560560
exc_info=False,
561561
)
562562

@@ -579,10 +579,8 @@ async def async_wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
579579
self._make_calling_record(name=func.__name__, arguments=args_repr, method="Awaiting")
580580
result = await func(*args, **kwargs)
581581
self._make_done_record(func.__name__, result)
582-
except BaseException as e:
583-
if isinstance(e, tuple(self.blacklisted_exceptions)):
584-
raise
585-
self._make_exc_record(name=func.__name__, arguments=args_repr)
582+
except Exception as e:
583+
self._make_exc_record(name=func.__name__, arguments=args_repr, exception=e)
586584
raise
587585
return result # type: ignore
588586

@@ -596,10 +594,8 @@ def wrapper(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
596594
self._make_calling_record(name=func.__name__, arguments=args_repr)
597595
result = func(*args, **kwargs)
598596
self._make_done_record(func.__name__, result)
599-
except BaseException as e:
600-
if isinstance(e, tuple(self.blacklisted_exceptions)):
601-
raise
602-
self._make_exc_record(name=func.__name__, arguments=args_repr)
597+
except Exception as e:
598+
self._make_exc_record(name=func.__name__, arguments=args_repr, exception=e)
603599
raise
604600
return result
605601

@@ -715,7 +711,8 @@ def logwrap( # noqa: F811
715711
:type spec: typing.Optional[typing.Callable]
716712
:param blacklisted_names: Blacklisted argument names. Arguments with this names will be skipped in log.
717713
:type blacklisted_names: typing.Optional[typing.Iterable[str]]
718-
:param blacklisted_exceptions: list of exceptions, which should be re-raised without producing log record.
714+
:param blacklisted_exceptions: list of exceptions, which should be re-raised
715+
without producing traceback and text log record.
719716
:type blacklisted_exceptions: typing.Optional[typing.Iterable[typing.Type[Exception]]]
720717
:param log_call_args: log call arguments before executing wrapped function.
721718
:type log_call_args: bool

logwrap/log_wrap.pyx

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,8 @@ cdef class LogWrap(class_decorator.BaseDecorator):
173173
:type spec: typing.Optional[typing.Callable]
174174
:param blacklisted_names: Blacklisted argument names. Arguments with this names will be skipped in log.
175175
:type blacklisted_names: typing.Optional[typing.Iterable[str]]
176-
:param blacklisted_exceptions: list of exception, which should be re-raised without producing log record.
176+
:param blacklisted_exceptions: list of exception, which should be re-raised
177+
without producing traceback and text log record.
177178
:type blacklisted_exceptions: typing.Optional[typing.Iterable[typing.Type[Exception]]]
178179
:param log_call_args: log call arguments before executing wrapped function.
179180
:type log_call_args: bool
@@ -364,25 +365,30 @@ cdef class LogWrap(class_decorator.BaseDecorator):
364365
msg=f"{method}: \n{name}({arguments if self.log_call_args else ''})",
365366
)
366367

367-
void _make_exc_record(self, str name, str arguments) except *:
368+
void _make_exc_record(self, str name, str arguments, Exception exception) except *:
368369
"""Make log record if exception raised.
369370
370371
:type name: str
371372
:type arguments: str
373+
:type exception: Exception
372374
"""
373375
exc_info = sys.exc_info()
374376
stack = traceback.extract_stack()
375377
full_tb = [elem for elem in stack if elem.filename != _CURRENT_FILE] # type: typing.List[traceback.FrameSummary]
376378
exc_line = traceback.format_exception_only(*exc_info[:2])
377379
# Make standard traceback string
378-
cdef str tb_text = "Traceback (most recent call last):\n" + "".join(traceback.format_list(full_tb)) + "".join(exc_line)
380+
cdef str tb_text = (
381+
f"Traceback (most recent call last):\n{''.join(traceback.format_list(full_tb))}{''.join(exc_line)}"
382+
if self.log_traceback and not isinstance(exception, tuple(self.blacklisted_exceptions))
383+
else exception.__class__.__name__
384+
)
379385

380386
self._logger.log(
381387
level=self.exc_level,
382388
msg=(
383389
f"Failed: \n"
384390
f"{name}({arguments if self.log_call_args_on_exc else ''})\n"
385-
f"{tb_text if self.log_traceback else ''}"
391+
f"{tb_text}"
386392
),
387393
exc_info=False,
388394
)
@@ -405,10 +411,8 @@ cdef class LogWrap(class_decorator.BaseDecorator):
405411
self._make_calling_record(name=func.__name__, arguments=args_repr, method="Awaiting")
406412
result = await func(*args, **kwargs)
407413
self._make_done_record(func.__name__, result)
408-
except BaseException as e:
409-
if isinstance(e, tuple(self.blacklisted_exceptions)):
410-
raise
411-
self._make_exc_record(name=func.__name__, arguments=args_repr)
414+
except Exception as e:
415+
self._make_exc_record(name=func.__name__, arguments=args_repr, exception=e)
412416
raise
413417
return result
414418

@@ -421,10 +425,8 @@ cdef class LogWrap(class_decorator.BaseDecorator):
421425
self._make_calling_record(name=func.__name__, arguments=args_repr)
422426
result = func(*args, **kwargs)
423427
self._make_done_record(func.__name__, result)
424-
except BaseException as e:
425-
if isinstance(e, tuple(self.blacklisted_exceptions)):
426-
raise
427-
self._make_exc_record(name=func.__name__, arguments=args_repr)
428+
except Exception as e:
429+
self._make_exc_record(name=func.__name__, arguments=args_repr, exception=e)
428430
raise
429431
return result
430432

@@ -475,7 +477,8 @@ def logwrap(
475477
:type spec: typing.Optional[typing.Callable]
476478
:param blacklisted_names: Blacklisted argument names. Arguments with this names will be skipped in log.
477479
:type blacklisted_names: typing.Optional[typing.Iterable[str]]
478-
:param blacklisted_exceptions: list of exceptions, which should be re-raised without producing log record.
480+
:param blacklisted_exceptions: list of exceptions, which should be re-raised
481+
without producing traceback and text log record.
479482
:type blacklisted_exceptions: typing.Optional[typing.Iterable[typing.Type[Exception]]]
480483
:param log_call_args: log call arguments before executing wrapped function.
481484
:type log_call_args: bool

test/test_log_wrap.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,7 @@ def func():
459459
level=logging.DEBUG,
460460
msg="Calling: \nfunc()"
461461
),
462+
mock.call(exc_info=False, level=40, msg=f'Failed: \nfunc()\n{TypeError.__name__}')
462463
],
463464
log.mock_calls,
464465
)

test/test_log_wrap_py3.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ def func():
134134
level=logging.DEBUG,
135135
msg="Awaiting: \nfunc()"
136136
),
137+
mock.call(exc_info=False, level=40, msg=f'Failed: \nfunc()\n{TypeError.__name__}')
137138
],
138139
log.mock_calls,
139140
)

test/test_log_wrap_py35.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ async def func():
130130
level=logging.DEBUG,
131131
msg="Awaiting: \nfunc()"
132132
),
133+
mock.call(exc_info=False, level=40, msg=f'Failed: \nfunc()\n{TypeError.__name__}')
133134
],
134135
log.mock_calls,
135136
)

0 commit comments

Comments
 (0)