+def _get_systemwide_abnormal_exit_handler(filename: str) -> FileHandler:
+ handler = FileHandler(filename)
+ handler.setFormatter(
+ MillisecondAwareFormatter(
+ fmt=_construct_logging_format(),
+ datefmt=config.config["logging_date_format"],
+ )
+ )
+ return handler
+
+
+def non_zero_return_value(ret: Any) -> bool:
+ """
+ Special method hooked from bootstrap.py to optionally keep a system-wide
+ record of non-zero python program exits.
+
+ Args:
+ ret: the return value
+ """
+ try:
+ record = config.config['logging_non_zero_exits_record_path']
+ if record:
+ logger = logging.getLogger()
+ handler = _get_systemwide_abnormal_exit_handler(record)
+ program = config.PROGRAM_NAME
+ args = config.ORIG_ARGV
+ with LoggingContext(logger, handlers=[handler], level=logging.ERROR) as log:
+ log.error('%s (%s) Exit %s', program, args, ret)
+ return True
+ except Exception:
+ pass
+ return False
+
+
+def unhandled_top_level_exception(
+ exc_type: type, exc_value: type, exc_tb: TracebackType
+) -> bool:
+ """
+ Special method hooked from bootstrap.py to optionally keep a system-wide
+ record of unhandled top level exceptions.
+
+ Args:
+ exc_type: the type of the unhandled exception
+ exc_value: the value passed to the exception's c'tor
+ exc_tb: the stack from where the exception was raised
+ """
+ try:
+ record = config.config['logging_unhandled_top_level_exceptions_record_path']
+ if record:
+ import traceback
+
+ logger = logging.getLogger()
+ handler = _get_systemwide_abnormal_exit_handler(record)
+ program = config.PROGRAM_NAME
+ args = config.ORIG_ARGV
+ tb = traceback.extract_tb(exc_tb)
+ original_frame = tb[-1]
+ raise_site_file = original_frame.filename
+ raise_site_lineno = original_frame.lineno
+ with LoggingContext(logger, handlers=[handler], level=logging.ERROR) as log:
+ log.error(
+ '%s (%s) unhandled top-level exception (type=%s(%s)) at %s:%s',
+ program,
+ args,
+ exc_type.__name__,
+ str(exc_value),
+ raise_site_file,
+ raise_site_lineno,
+ )
+ return True
+ except Exception:
+ pass
+ return False
+
+