Aller au contenu

Rich

Rich is a Python library for rich text and beautiful formatting in the terminal.

Installer Rich

$ pip install rich

Utiliser Rich pour ajouter de la coloration syntaxique à vos logs

Enrichir les messages d'erreur en console

# Rich traceback in the REPL:
from rich import traceback

_ = traceback.install()

Enrichir les messages d'erreur dans les logs

# Log to sys.stderr with rich text:
import logging
from rich.logging import RichHandler

logging.basicConfig(
    level=logging.DEBUG,
    format="%(message)s",
    handlers=[RichHandler(rich_tracebacks=True)],
)

Exemple d'utilisation

import logging

logger = logging.getLogger(__name__)


def main() -> int:
    try:
        1 / 0  # Deliberate error!
    except ZeroDivisionError as e:
        logger.exception(e)
        return 1
    return 0


if __name__ == "__main__":
    # Rich traceback in the REPL:
    from rich import traceback

    _ = traceback.install()

    # Log to sys.stderr with rich text:
    from rich.logging import RichHandler

    logging.basicConfig(
        level=logging.DEBUG,
        format="%(message)s",
        handlers=[RichHandler(rich_tracebacks=True)],
    )

    # Call main function:
    import sys

    sys.exit(main())

Ressources