diff --git a/homeassistant/bootstrap.py b/homeassistant/bootstrap.py index 9e375c7fdb8..96af205e4e0 100644 --- a/homeassistant/bootstrap.py +++ b/homeassistant/bootstrap.py @@ -624,13 +624,16 @@ async def async_enable_logging( if log_file is None: default_log_path = hass.config.path(ERROR_LOG_FILENAME) - if "SUPERVISOR" in os.environ: - _LOGGER.info("Running in Supervisor, not logging to file") + if "SUPERVISOR" in os.environ and "HA_DUPLICATE_LOG_FILE" not in os.environ: # Rename the default log file if it exists, since previous versions created # it even on Supervisor - if os.path.isfile(default_log_path): - with contextlib.suppress(OSError): - os.rename(default_log_path, f"{default_log_path}.old") + def rename_old_file() -> None: + """Rename old log file in executor.""" + if os.path.isfile(default_log_path): + with contextlib.suppress(OSError): + os.rename(default_log_path, f"{default_log_path}.old") + + await hass.async_add_executor_job(rename_old_file) err_log_path = None else: err_log_path = default_log_path diff --git a/tests/test_bootstrap.py b/tests/test_bootstrap.py index 8f6a59a2915..e3d32354e49 100644 --- a/tests/test_bootstrap.py +++ b/tests/test_bootstrap.py @@ -130,8 +130,16 @@ async def test_async_enable_logging( cleanup_log_files() +@pytest.mark.parametrize( + ("extra_env", "log_file_count", "old_log_file_count"), + [({}, 0, 1), ({"HA_DUPLICATE_LOG_FILE": "1"}, 1, 0)], +) async def test_async_enable_logging_supervisor( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + extra_env: dict[str, str], + log_file_count: int, + old_log_file_count: int, ) -> None: """Test to ensure the default log file is not created on Supervisor installations.""" @@ -141,14 +149,14 @@ async def test_async_enable_logging_supervisor( assert len(glob.glob(ARG_LOG_FILE)) == 0 with ( - patch.dict(os.environ, {"SUPERVISOR": "1"}), + patch.dict(os.environ, {"SUPERVISOR": "1", **extra_env}), patch( "homeassistant.bootstrap.async_activate_log_queue_handler" ) as mock_async_activate_log_queue_handler, patch("logging.getLogger"), ): await bootstrap.async_enable_logging(hass) - assert len(glob.glob(CONFIG_LOG_FILE)) == 0 + assert len(glob.glob(CONFIG_LOG_FILE)) == log_file_count mock_async_activate_log_queue_handler.assert_called_once() mock_async_activate_log_queue_handler.reset_mock() @@ -162,9 +170,10 @@ async def test_async_enable_logging_supervisor( await hass.async_add_executor_job(write_log_file) assert len(glob.glob(CONFIG_LOG_FILE)) == 1 assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == 0 + await bootstrap.async_enable_logging(hass) - assert len(glob.glob(CONFIG_LOG_FILE)) == 0 - assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == 1 + assert len(glob.glob(CONFIG_LOG_FILE)) == log_file_count + assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == old_log_file_count mock_async_activate_log_queue_handler.assert_called_once() mock_async_activate_log_queue_handler.reset_mock()