Skip to content

Commit

Permalink
core/logging: set exc_info during logging automatically
Browse files Browse the repository at this point in the history
  • Loading branch information
karlicoss committed Jan 17, 2023
1 parent df1a167 commit 48f25cf
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/promnesia/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def do_index(
if len(errors) > 0:
logger.error('%d errors, printing them out:', len(errors))
for e in errors:
logger.error(' %s', e, exc_info=e)
logger.exception(e)
logger.error('%d errors, exit code 1', len(errors))
sys.exit(1)

Expand Down
19 changes: 19 additions & 0 deletions src/promnesia/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ def setup_logger(logger: logging.Logger, level: LevelIsh) -> None:
formatter = logging.Formatter(fmt=FORMAT_NOCOLOR, datefmt=DATEFMT)
use_logzero = False

logger.addFilter(AddExceptionTraceback())
if use_logzero and not COLLAPSE_DEBUG_LOGS: # all set, nothing to do
# 'simple' setup
logzero.setup_logger(logger.name, level=lvl, formatter=formatter)
Expand Down Expand Up @@ -104,6 +105,24 @@ def isEnabledFor_lazyinit(*args, logger=logger, orig=logger.isEnabledFor, **kwar
return cast(LazyLogger, logger)


# by default, logging.exception isn't logging traceback
# which is a bit annoying since we have to
# also see https://stackoverflow.com/questions/75121925/why-doesnt-python-logging-exception-method-log-traceback-by-default
# tod also amend by post about defensive error handling?
class AddExceptionTraceback(logging.Filter):
def filter(self, record):
s = super().filter(record)
if s is False:
return False
if record.levelname == 'ERROR':
exc = record.msg
if isinstance(exc, BaseException):
if record.exc_info is None or record.exc_info == (None, None, None):
exc_info = (type(exc), exc, exc.__traceback__)
record.exc_info = exc_info
return s


# todo also save full log in a file?
class CollapseDebugHandler(logging.StreamHandler):
'''
Expand Down

0 comments on commit 48f25cf

Please sign in to comment.