From 059046b0dbd82534054dd49d8122a25e2cd955ec Mon Sep 17 00:00:00 2001 From: Engel Nyst Date: Wed, 13 Nov 2024 20:21:10 +0100 Subject: [PATCH] strip escape from file logs --- openhands/core/logger.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/openhands/core/logger.py b/openhands/core/logger.py index 20a4a4d6581a..1450e503515e 100644 --- a/openhands/core/logger.py +++ b/openhands/core/logger.py @@ -1,3 +1,4 @@ +import copy import logging import os import re @@ -45,6 +46,29 @@ } +class NoColorFormatter(logging.Formatter): + """Formatter for non-colored logging in files.""" + + def format(self, record: logging.LogRecord) -> str: + # Create a deep copy of the record to avoid modifying the original + new_record: logging.LogRecord = copy.deepcopy(record) + # Strip ANSI color codes from the message + new_record.msg = strip_ansi(new_record.msg) + + return super().format(new_record) + + +def strip_ansi(s: str) -> str: + """ + Removes ANSI escape sequences from str, as defined by ECMA-048 in + http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf + # https://github.com/ewen-lbh/python-strip-ansi/blob/master/strip_ansi/__init__.py + """ + pattern = re.compile(r'\x1B\[\d+(;\d+){0,2}m') + stripped = pattern.sub('', s) + return stripped + + class ColoredFormatter(logging.Formatter): def format(self, record): msg_type = record.__dict__.get('msg_type') @@ -70,7 +94,7 @@ def format(self, record): return super().format(record) -file_formatter = logging.Formatter( +file_formatter = NoColorFormatter( '%(asctime)s - %(name)s:%(levelname)s: %(filename)s:%(lineno)s - %(message)s', datefmt='%H:%M:%S', )