From 6ff86dd53e84edf5ea6c60ef1790d30d48865b61 Mon Sep 17 00:00:00 2001 From: Alexsander Hamir Date: Tue, 27 Jan 2026 16:00:49 -0800 Subject: [PATCH] fix: prevent logging errors during worker shutdown Added pre-flight checks in _safe_log to verify logger handlers are valid and their streams are open before attempting to log. This prevents 'I/O operation on closed file' errors during pytest-xdist worker shutdown when atexit handlers run after Python has closed file handles. --- litellm/litellm_core_utils/logging_worker.py | 22 ++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/litellm/litellm_core_utils/logging_worker.py b/litellm/litellm_core_utils/logging_worker.py index 13a83956edd..d5eca9eeb55 100644 --- a/litellm/litellm_core_utils/logging_worker.py +++ b/litellm/litellm_core_utils/logging_worker.py @@ -415,6 +415,28 @@ class LoggingWorker: """ Safely log a message during shutdown, suppressing errors if logging is closed. """ + # Check if logger has valid handlers before attempting to log + # During shutdown, handlers may be closed, causing ValueError when writing + if not hasattr(verbose_logger, 'handlers') or not verbose_logger.handlers: + return + + # Check if any handler has a valid stream + has_valid_handler = False + for handler in verbose_logger.handlers: + try: + if hasattr(handler, 'stream') and handler.stream and not handler.stream.closed: + has_valid_handler = True + break + elif not hasattr(handler, 'stream'): + # Non-stream handlers (like NullHandler) are always valid + has_valid_handler = True + break + except (AttributeError, ValueError): + continue + + if not has_valid_handler: + return + try: if level == "debug": verbose_logger.debug(message)