Skip to content

Commit

Permalink
Merge pull request alan-turing-institute#2231 from alan-turing-instit…
Browse files Browse the repository at this point in the history
…ute/ansi_logfile

Remove ANSI escape sequences from logfile
  • Loading branch information
JimMadge authored Oct 9, 2024
2 parents 0f9d353 + 42d46c1 commit eede40f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
11 changes: 9 additions & 2 deletions data_safe_haven/logging/plain_file_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,23 @@ def __init__(self, *args: Any, **kwargs: Any):
super().__init__(*args, **kwargs)

@staticmethod
def strip_formatting(input_string: str) -> str:
def strip_rich_formatting(input_string: str) -> str:
"""Strip console markup formatting from a string"""
text = Text.from_markup(input_string)
text.spans = []
return str(text)

@staticmethod
def strip_ansi_escapes(input_string: str) -> str:
"""Strip ANSI escape sequences from a string"""
text = Text.from_ansi(input_string)
text.spans = []
return str(text)

def emit(self, record: logging.LogRecord) -> None:
"""Emit a record without formatting"""
if isinstance(record.msg, Text):
# Convert rich.text.Text objects to strings
record.msg = str(record.msg)
record.msg = self.strip_formatting(record.msg)
record.msg = self.strip_ansi_escapes(self.strip_rich_formatting(record.msg))
super().emit(record)
13 changes: 11 additions & 2 deletions tests/logging/test_plain_file_handler.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import pytest

from data_safe_haven.logging.plain_file_handler import PlainFileHandler


class TestPlainFileHandler:
def test_strip_formatting(self):
assert PlainFileHandler.strip_formatting("[green]hello[/]") == "hello"
def test_strip_rich_formatting(self):
assert PlainFileHandler.strip_rich_formatting("[green]Hello[/]") == "Hello"

@pytest.mark.parametrize("escape", ["\033", "\x1B", "\u001b", "\x1B"])
def test_strip_ansi_escapes(self, escape):
assert (
PlainFileHandler.strip_ansi_escapes(f"{escape}[31;1;4mHello{escape}[0m")
== "Hello"
)

0 comments on commit eede40f

Please sign in to comment.