-
-
Notifications
You must be signed in to change notification settings - Fork 11
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add custom logger that does soft-wrapping (#10)
Fixes: #6 Related: Textualize/rich#438 Related: Textualize/rich#344
- Loading branch information
Showing
4 changed files
with
196 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
"""Implements enriched RichHandler""" | ||
from datetime import datetime | ||
from typing import TYPE_CHECKING, Iterable, Optional | ||
|
||
from rich.logging import RichHandler as OriginalRichHandler | ||
from rich.text import Text, TextType | ||
|
||
if TYPE_CHECKING: | ||
from rich.console import Console, ConsoleRenderable | ||
|
||
|
||
# Based on https://github.com/willmcgugan/rich/blob/master/rich/_log_render.py | ||
class FluidLogRender: # pylint: disable=too-few-public-methods | ||
"""Renders log by not using columns and avoiding any wrapping.""" | ||
|
||
def __init__( | ||
self, | ||
show_time: bool = False, | ||
show_level: bool = False, | ||
show_path: bool = True, | ||
time_format: str = "[%x %X]", | ||
) -> None: | ||
self.show_time = show_time | ||
self.show_level = show_level | ||
self.show_path = show_path | ||
self.time_format = time_format | ||
self._last_time: Optional[str] = None | ||
|
||
def __call__( # pylint: disable=too-many-arguments | ||
self, | ||
console: "Console", | ||
renderables: Iterable["ConsoleRenderable"], | ||
log_time: datetime = None, | ||
time_format: str = None, | ||
level: TextType = "", | ||
path: str = None, | ||
line_no: int = None, | ||
link_path: str = None, | ||
) -> Text: | ||
|
||
result = Text() | ||
if self.show_time: | ||
if log_time is None: | ||
log_time = datetime.now() | ||
log_time_display = log_time.strftime(time_format or self.time_format) + " " | ||
if log_time_display == self._last_time: | ||
result += Text(" " * len(log_time_display)) | ||
else: | ||
result += Text(log_time_display) | ||
self._last_time = log_time_display | ||
if self.show_level: | ||
if not isinstance(level, Text): | ||
level = Text(level) | ||
if len(level) < 8: | ||
level += " " * (8 - len(level)) | ||
result += level | ||
|
||
for elem in renderables: | ||
result += elem | ||
|
||
if self.show_path and path: | ||
path_text = Text(" ", style="repr.filename") | ||
path_text.append( | ||
path, style=f"link file://{link_path}" if link_path else "" | ||
) | ||
if line_no: | ||
path_text.append(f":{line_no}") | ||
result += path_text | ||
|
||
return result | ||
|
||
|
||
class RichHandler(OriginalRichHandler): | ||
"""Enriched handler that does not wrap.""" | ||
|
||
def __init__(self, *args, **kwargs): # type: ignore | ||
super().__init__(*args, **kwargs) | ||
# RichHandler constructor does not allow custom renderer | ||
# https://github.com/willmcgugan/rich/issues/438 | ||
self._log_render = FluidLogRender( | ||
show_time=kwargs.get("show_time", False), | ||
show_level=kwargs.get("show_level", True), | ||
show_path=kwargs.get("show_path", False), | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
"""Tests related to enriched RichHandler""" | ||
import io | ||
import logging | ||
import re | ||
from typing import Tuple, Union | ||
|
||
import pytest | ||
|
||
from enrich.console import Console | ||
from enrich.logging import RichHandler | ||
|
||
|
||
def strip_ansi_escape(text: Union[str, bytes]) -> str: | ||
"""Remove all ANSI escapes from string or bytes. | ||
If bytes is passed instead of string, it will be converted to string | ||
using UTF-8. | ||
""" | ||
if isinstance(text, bytes): | ||
text = text.decode("utf-8") | ||
|
||
return re.sub(r"\x1b[^m]*m", "", text) | ||
|
||
|
||
@pytest.fixture(name="rich_logger") | ||
def rich_logger_fixture() -> Tuple[logging.Logger, logging.Handler]: | ||
"""Returns tuple with logger and handler to be tested.""" | ||
rich_handler = RichHandler( | ||
console=Console( | ||
file=io.StringIO(), | ||
force_terminal=True, | ||
width=80, | ||
color_system="truecolor", | ||
soft_wrap=True, | ||
), | ||
enable_link_path=False, | ||
) | ||
|
||
logging.basicConfig( | ||
level="NOTSET", format="%(message)s", datefmt="[DATE]", handlers=[rich_handler] | ||
) | ||
rich_log = logging.getLogger("rich") | ||
rich_log.addHandler(rich_handler) | ||
return (rich_log, rich_handler) | ||
|
||
|
||
def test_logging(rich_logger) -> None: | ||
"""Test that logger does not wrap.""" | ||
|
||
(logger, rich_handler) = rich_logger | ||
|
||
text = 10 * "x" # a long text that would likely wrap on a normal console | ||
logger.error("%s %s", text, 123) | ||
|
||
# verify that the long text was not wrapped | ||
output = strip_ansi_escape(rich_handler.console.file.getvalue()) | ||
assert text in output | ||
assert "ERROR" in output | ||
assert "\n" not in output[:-1] | ||
|
||
|
||
if __name__ == "__main__": | ||
handler = RichHandler( | ||
console=Console( | ||
force_terminal=True, | ||
width=55510, # this is expected to have no effect | ||
color_system="truecolor", | ||
soft_wrap=True, | ||
), | ||
enable_link_path=False, | ||
show_time=True, | ||
show_level=True, | ||
show_path=True, | ||
) | ||
logging.basicConfig( | ||
level="NOTSET", | ||
format="%(message)s", | ||
# datefmt="[DATE]", | ||
handlers=[handler], | ||
) | ||
log = logging.getLogger("rich") | ||
# log.addHandler(handler) | ||
data = {"foo": "text", "bar": None, "number": 123} | ||
log.error("This was a long error") | ||
log.warning("This was warning %s apparently", 123) | ||
log.info("Having info is good") | ||
log.debug("Some kind of debug message %s", None) | ||
log.info("Does this dictionary %s render ok?", data) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters