rich icon indicating copy to clipboard operation
rich copied to clipboard

[BUG] Highlighter handling between Console and RichHandler inconsistent.

Open maltevesper opened this issue 3 months ago • 1 comments

Highlighting differs in an odd way between print and logging using the same console object, depending on the highlighter implementation. From a users perspective it is not clear at all where the difference between class A and B is, yet they behave differnetly as noted below:

class A(ReprHighlighter):
    highlights = [*ReprHighlighter.highlights, "myhighlight"]

class B(ReprHighlighter):
    def __init__(self):
        super().__init__()
        self.__class__.highlights.append("myhighligh")

minimal working example

import logging
import re
from typing import Any, ClassVar

from rich.console import Console
from rich.highlighter import Highlighter, ReprHighlighter
from rich.logging import RichHandler
from rich.theme import Theme


class HashHighlighter(ReprHighlighter):
    """This one only works if applied directly to the logging handler."""

    highlights: ClassVar[list[str | re.Pattern[str]]] = [  # type: ignore[assignment]
        *ReprHighlighter.highlights,
        re.compile(r"\b(?P<git_hash>FOO)\b"),
    ]


class HashHighlighterWithInit(ReprHighlighter):
    """For this one it is sufficient to install it on the console object."""

    def __init__(self) -> None:
        super().__init__()
        self.__class__.highlights.append(
            re.compile(r"\b(?P<git_hash>FOO)\b"),
        )


sample_message = "A git hash FOO"


def demo(highlighter: Highlighter, fix: dict[str, Any] = {}) -> None:
    console = Console(highlighter=highlighter)
    console.push_theme(Theme({"repr.git_hash": "bold magenta"}))
    console.print(sample_message)
    logging.basicConfig(
        level=logging.INFO,
        format="%(message)s",
        datefmt="[%X]",
        handlers=[
            RichHandler(console=console, **fix)
        ],  # , highlighter=HashHighlighter()
    )
    logging.warning(sample_message)


demo(HashHighlighter())  # note how the logging output is not highlighted
demo(HashHighlighterWithInit()) # here logging output is highlighted
demo(HashHighlighter(), {"highlighter": HashHighlighter()}) # with this workaround (adding the highlighter on rich handler rather than on console), the otherwise none working highlighter starts to work with logging too

maltevesper avatar Nov 17 '25 07:11 maltevesper

We found the following entries in the FAQ which you may find helpful:

Feel free to close this issue if you found an answer in the FAQ. Otherwise, please give us a little time to review.

Rich was created by Will McGugan. Consider sponsoring Will's work on Rich.

This is an automated reply, generated by FAQtory

github-actions[bot] avatar Nov 17 '25 07:11 github-actions[bot]