def reconfigure(new_options: Dict[str, Any]): """Reconfigure console options.""" global console_options # pylint: disable=global-statement global console_stderr # pylint: disable=global-statement console_options = new_options rich.reconfigure(**new_options) # see https://github.com/willmcgugan/rich/discussions/484#discussioncomment-200182 tmp_console = Console(**console_options, stderr=True) console_stderr.__dict__ = tmp_console.__dict__
def _init_progress(self, trainer): if self.is_enabled and (self.progress is None or self._progress_stopped): self._reset_progress_bar_ids() reconfigure(**self._console_kwargs) self._console = get_console() self._console.clear_live() self._metric_component = MetricsTextColumn(trainer, self.theme.metrics) self.progress = CustomProgress( *self.configure_columns(trainer), self._metric_component, auto_refresh=False, disable=self.is_disabled, console=self._console, ) self.progress.start() # progress has started self._progress_stopped = False
def init_logging(level: int, location: pathlib.Path, cli_flags: argparse.Namespace) -> None: root_logger = logging.getLogger() base_logger = logging.getLogger("red") base_logger.setLevel(level) dpy_logger = logging.getLogger("discord") dpy_logger.setLevel(logging.WARNING) warnings_logger = logging.getLogger("py.warnings") warnings_logger.setLevel(logging.WARNING) rich_console = rich.get_console() rich.reconfigure(tab_size=4) rich_console.push_theme( Theme({ "log.time": Style(dim=True), "logging.level.warning": Style(color="yellow"), "logging.level.critical": Style(color="white", bgcolor="red"), "repr.number": Style(color="cyan"), "repr.url": Style(underline=True, italic=True, bold=False, color="cyan"), })) rich_console.file = sys.stdout # This is terrible solution, but it's the best we can do if we want the paths in tracebacks # to be visible. Rich uses `pygments.string` style which is fine, but it also uses # this highlighter which dims most of the path and therefore makes it unreadable on Mac. PathHighlighter.highlights = [] enable_rich_logging = False if isatty(0) and cli_flags.rich_logging is None: # Check if the bot thinks it has a active terminal. enable_rich_logging = True elif cli_flags.rich_logging is True: enable_rich_logging = True file_formatter = logging.Formatter( "[{asctime}] [{levelname}] {name}: {message}", datefmt="%Y-%m-%d %H:%M:%S", style="{") if enable_rich_logging is True: rich_formatter = logging.Formatter("{message}", datefmt="[%X]", style="{") stdout_handler = RedRichHandler( rich_tracebacks=True, show_path=False, highlighter=NullHighlighter(), tracebacks_extra_lines=cli_flags.rich_traceback_extra_lines, tracebacks_show_locals=cli_flags.rich_traceback_show_locals, tracebacks_theme=(PygmentsSyntaxTheme(FixedMonokaiStyle) if rich_console.color_system == "truecolor" else ANSISyntaxTheme(SYNTAX_THEME)), ) stdout_handler.setFormatter(rich_formatter) else: stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(file_formatter) root_logger.addHandler(stdout_handler) logging.captureWarnings(True) if not location.exists(): location.mkdir(parents=True, exist_ok=True) # Rotate latest logs to previous logs previous_logs: List[pathlib.Path] = [] latest_logs: List[Tuple[pathlib.Path, str]] = [] for path in location.iterdir(): match = re.match(r"latest(?P<part>-part\d+)?\.log", path.name) if match: part = match.groupdict(default="")["part"] latest_logs.append((path, part)) match = re.match(r"previous(?:-part\d+)?.log", path.name) if match: previous_logs.append(path) # Delete all previous.log files for path in previous_logs: path.unlink() # Rename latest.log files to previous.log for path, part in latest_logs: path.replace(location / f"previous{part}.log") latest_fhandler = RotatingFileHandler( stem="latest", directory=location, maxBytes=1_000_000, # About 1MB per logfile backupCount=MAX_OLD_LOGS, encoding="utf-8", ) all_fhandler = RotatingFileHandler( stem="red", directory=location, maxBytes=1_000_000, backupCount=MAX_OLD_LOGS, encoding="utf-8", ) for fhandler in (latest_fhandler, all_fhandler): fhandler.setFormatter(file_formatter) root_logger.addHandler(fhandler)
def test_reconfigure_console(): rich.reconfigure(width=100) assert rich.get_console().width == 100