Exemple #1
0
def patch_log_module(logger: logging.Logger,
                     module_name: str) -> collections.abc.Iterator[None]:
    """Patch logs using `logger` within this context manager to use `module_name` as the module name."""
    original_find_caller = logger.findCaller

    def patched_caller(self: logging.Logger, stack_info: bool,
                       stack_level: int) -> tuple[str, int, str, str] | None:
        """Patch filename on logs after this was applied to be `module_name`."""
        _, lno, func, sinfo = original_find_caller(stack_info, stack_level)
        return module_name, lno, func, sinfo

    logger.findCaller = MethodType(patched_caller, logger)
    try:
        yield
    finally:
        logger.findCaller = original_find_caller