Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[BUG] Highlighter handling between Console and RichHandler inconsistent. #3887

@maltevesper

Description

@maltevesper

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions