Rich is a Python library for writing rich text (with color and style) to the terminal, and for displaying advanced content such as tables, markdown, and syntax highlighted code.
Rich provides RichHandler, a logging handler for python's logging module which will format and colorize text written by the module.
However, RichHandler writes to stdout by default. More specifically, it writes to a rich Console object which, by default, writes to stdout.
To make RichHandler write to stderr by default, you must pass in a Console object which has been configured to write to stderr:
import logging from rich.console import Console from rich.logging import RichHandler DATEFMT = "%Y-%m-%dT%H:%M:%SZ" FORMAT = "%(message)s" logging.basicConfig( level="NOTSET", format=FORMAT, datefmt=DATEFMT, handlers=[RichHandler(console=Console(stderr=True))], ) logger = logging.getLogger(__name__) logger.info("Hello, World!")
import logging import sys from rich.console import Console from rich.logging import RichHandler DATEFMT = "%Y-%m-%dT%H:%M:%SZ" if sys.stderr.isatty(): handler = RichHandler(console=Console(stderr=True)) FORMAT = "%(message)s" else: FORMAT = "%(asctime)s\t%(levelname)s\t%(message)s" handler = logging.StreamHandler() logging.basicConfig( level="NOTSET", format=FORMAT, datefmt=DATEFMT, handlers=[handler] ) logger = logging.getLogger(__name__) logger.info("Hello, World!")
Comments