diff --git a/app/utils/logging.py b/app/utils/logging.py index e56f2ed6..57db13f7 100644 --- a/app/utils/logging.py +++ b/app/utils/logging.py @@ -25,7 +25,7 @@ class TaskLogCollector(logging.Handler): try: msg = self.format(record) # Extract task_id from messages formatted as "[task_id] ..." - if msg and "[" in msg: + if msg and "[" in msg and "]" in msg: start = msg.index("[") end = msg.index("]", start) task_id = msg[start + 1 : end].strip() @@ -76,7 +76,7 @@ def log_task_progress(task_id, step_name, status, message=None, file_id=None, de If not provided, buffered logger output is used automatically. """ # Auto-capture buffered log output when no explicit detail is given - if detail is None and task_id: + if not detail and task_id: _ensure_collector_installed() collected = _collector.drain(task_id) if collected: diff --git a/tests/test_logging_utils.py b/tests/test_logging_utils.py index 26ce24e5..a4906841 100644 --- a/tests/test_logging_utils.py +++ b/tests/test_logging_utils.py @@ -257,3 +257,23 @@ class TestTaskLogCollector: assert collector.drain("OK") == "" logger.removeHandler(collector) + + def test_collector_handles_malformed_brackets(self): + """Test that the collector handles messages with [ but no ].""" + from app.utils.logging import TaskLogCollector + + collector = TaskLogCollector() + collector.setFormatter(logging.Formatter("%(message)s")) + + logger = logging.getLogger("test_malformed") + logger.addHandler(collector) + logger.setLevel(logging.DEBUG) + + logger.info("[no closing bracket") + logger.info("no brackets at all") + logger.info("") + + # Should not raise and should not buffer anything + assert collector.drain("no closing bracket") == "" + + logger.removeHandler(collector)