Skip to content

phoenixpackagecleanup.utils.logging_utils

Logging utilities.

Functions:

Name Description
init_logging

(Re-)initialize all loggers.

log_uncaught_exceptions

Make all uncaught exception to be logged by the default logger.

init_logging

init_logging(log_header_str, log_filename, log_level)

(Re-)initialize all loggers.

Source code in src/phoenixpackagecleanup/utils/logging_utils.py
def init_logging(log_header_str: str, log_filename: Path | None, log_level: LOGGING_LEVELS) -> None:
    """(Re-)initialize all loggers."""
    # log all warnings from the warnings module.
    logging.captureWarnings(True)  # noqa: FBT003 boolean argument is in standard library
    log_uncaught_exceptions()  # log all uncaught exceptions as well

    logging_format = f"%(asctime)s %(levelname)s {log_header_str} %(pathname)s:%(lineno)s:%(funcName)s %(message)s"
    handlers = []
    if log_filename is not None:  # write log to file
        handlers.append(logging.FileHandler(log_filename))
    else:  # write log to standard output and error
        # WARNING: this could cause freezing due to output pipes been full if this is called as a subprocess !
        handlers.append(logging.StreamHandler())
    logging.basicConfig(
        level=log_level.name,
        format=logging_format,
        handlers=handlers,
        force=True,
    )
    logger = logging.getLogger(__name__)
    logger.info("Logging configured - start logging")

log_uncaught_exceptions

log_uncaught_exceptions()

Make all uncaught exception to be logged by the default logger.

Keyboard exceptions and children classes are not logged so one can kill the program with ctr+C.

Source code in src/phoenixpackagecleanup/utils/logging_utils.py
def log_uncaught_exceptions() -> None:
    """Make all uncaught exception to be logged by the default logger.

    Keyboard exceptions and children classes are not logged so one can kill the program with ctr+C.
    """

    def handle_exception(
        exc_type: type[BaseException], exc_value: BaseException, exc_traceback: TracebackType | None
    ) -> None:
        if not issubclass(exc_type, KeyboardInterrupt):
            logger = logging.getLogger(__name__)
            logger.critical("Uncaught exception", exc_info=(exc_type, exc_value, exc_traceback))

        sys.__excepthook__(exc_type, exc_value, exc_traceback)

    sys.excepthook = handle_exception