Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions app/utils/logging_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,14 @@ def format(self, record: logging.LogRecord) -> str:
Formatted log message including ANSI color codes.
"""

original_levelname = record.levelname
level_color = self.COLORS.get(record.levelno, "")
record.levelname = f"{level_color}{record.levelname}{self.RESET}"
return super().format(record)
if level_color:
record.levelname = f"{level_color}{record.levelname}{self.RESET}"
try:
return super().format(record)
finally:
record.levelname = original_levelname


class RateLimitFilter(logging.Filter):
Expand Down
31 changes: 31 additions & 0 deletions tests/test_color_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,37 @@ def test_format_includes_ansi_codes(self):
self.assertIn("\033[", output)
self.assertIn("boom", output)

def test_plain_handler_is_uncolored_with_colored_sibling(self):
logger = logging.getLogger("color_test_plain")
colored_stream = io.StringIO()
plain_stream = io.StringIO()
colored_handler = logging.StreamHandler(colored_stream)
colored_handler.setFormatter(ColorFormatter("%(levelname)s:%(message)s"))
plain_handler = logging.StreamHandler(plain_stream)
plain_handler.setFormatter(logging.Formatter("%(levelname)s:%(message)s"))
logger.setLevel(logging.INFO)
original_propagate = logger.propagate
logger.propagate = False
logger.addHandler(colored_handler)
logger.addHandler(plain_handler)

try:
logger.warning("mixed output")
finally:
logger.removeHandler(colored_handler)
logger.removeHandler(plain_handler)
colored_handler.close()
plain_handler.close()
logger.propagate = original_propagate

colored_output = colored_stream.getvalue().strip()
Comment on lines +46 to +50

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Read StringIO after closing underlying stream

The regression test closes both handlers, but StreamHandler.close() also closes the attached StringIO. When execution reaches colored_stream.getvalue().strip() the stream is already closed and Python raises ValueError: I/O operation on closed file, so the test never reaches its assertions. Fetch the buffered contents before calling close() (or avoid closing the handlers) so the test exercises the behavior it is meant to verify.

Useful? React with 👍 / 👎.

plain_output = plain_stream.getvalue().strip()

self.assertIn("\033[", colored_output)
self.assertIn("mixed output", colored_output)
self.assertNotIn("\033[", plain_output)
self.assertIn("mixed output", plain_output)


if __name__ == "__main__":
unittest.main()
Loading