A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: safer windows logging on PermissionErrors (#6735)
Myles Scolnickd08dbdd5bf68
diff --git a/marimo/_loggers.py b/marimo/_loggers.pyindex 51079b4d1e..1ac88889b1 100644--- a/marimo/_loggers.py+++ b/marimo/_loggers.py@@ -41,6 +41,35 @@ _LOG_FORMATTER = LogFormatter()_LOGGERS: dict[str, logging.Logger] = {}+class WindowsSafeRotatingFileHandler(TimedRotatingFileHandler):+ """+ A Windows-compatible rotating file handler that closes the file+ before rotation to avoid PermissionError on Windows.++ On Windows, TimedRotatingFileHandler.doRollover() can fail with+ PermissionError when attempting to rename a file that's still open+ by another process or handler.+ """++ def doRollover(self) -> None:+ """+ Override doRollover to close the stream before rotation on Windows.+ """+ if self.stream:+ self.stream.close()+ self.stream = None # type: ignore[assignment]+ try:+ super().doRollover()+ except PermissionError:+ # If rotation fails, log the error but don't crash+ # The log file will continue to grow until the lock is released+ pass+ finally:+ # Reopen the stream+ if self.stream is None:+ self.stream = self._open()++def log_level_string_to_int(level: str) -> int:level = level.upper()if level == "DEBUG":@@ -160,10 +189,19 @@ def make_log_directory() -> None:def _file_handler() -> logging.FileHandler:+ from marimo._utils.platform import is_windows+make_log_directory()+ # Use Windows-safe handler on Windows to avoid PermissionError during rotation+ handler_class = (+ WindowsSafeRotatingFileHandler+ if is_windows()+ else TimedRotatingFileHandler+ )+# We log to the same file daily, and keep the last 7 days of logs- file_handler = TimedRotatingFileHandler(+ file_handler = handler_class(get_log_directory() / "marimo.log",when="D",interval=1,diff --git a/tests/test_loggers.py b/tests/test_loggers.pyindex c5fc87cf72..31f4928f14 100644--- a/tests/test_loggers.py+++ b/tests/test_loggers.py@@ -11,6 +11,7 @@ import pytestfrom marimo._loggers import (_LOG_LEVEL,_LOGGERS,+ WindowsSafeRotatingFileHandler,get_log_directory,get_logger,make_log_directory,@@ -117,6 +118,61 @@ def test_handler_levels():assert file_handler.level == logging.DEBUG+def test_windows_safe_handler(tmp_path: Path):+ """Test that WindowsSafeRotatingFileHandler handles rotation gracefully."""+ log_file = tmp_path / "test.log"++ # Create handler+ handler = WindowsSafeRotatingFileHandler(+ log_file,+ when="S", # Rotate every second for testing+ interval=1,+ backupCount=3,+ encoding="utf-8",+ )++ # Write some logs+ logger = logging.getLogger("test_windows")+ logger.addHandler(handler)+ logger.setLevel(logging.INFO)++ logger.info("Test message 1")+ logger.info("Test message 2")++ # Test that doRollover doesn't crash even with PermissionError+ try:+ handler.doRollover()+ # Should succeed or gracefully handle errors+ assert True+ except PermissionError:+ # Should not raise PermissionError+ pytest.fail("WindowsSafeRotatingFileHandler raised PermissionError")+ finally:+ handler.close()+ logger.removeHandler(handler)+++def test_file_handler_uses_windows_safe_on_windows(tmp_path: Path):+ """Test that _file_handler uses WindowsSafeRotatingFileHandler on Windows."""+ from marimo._loggers import _file_handler++ # Test on Windows+ with patch("sys.platform", "win32"):+ with patch("marimo._loggers.get_log_directory", return_value=tmp_path):+ handler = _file_handler()+ assert isinstance(handler, WindowsSafeRotatingFileHandler)+ handler.close()++ # Test on non-Windows+ with patch("sys.platform", "linux"):+ with patch("marimo._loggers.get_log_directory", return_value=tmp_path):+ handler = _file_handler()+ assert isinstance(handler, TimedRotatingFileHandler)+ # Should not be the Windows-safe subclass on non-Windows+ assert not isinstance(handler, WindowsSafeRotatingFileHandler)+ handler.close()++@pytest.fixture(autouse=True)def clear_loggers():# Clear the logger cache before each test