diff --git a/ddtrace/contrib/internal/pytest/_plugin_v2.py b/ddtrace/contrib/internal/pytest/_plugin_v2.py index 5be675c30df..e7cb4a50e84 100644 --- a/ddtrace/contrib/internal/pytest/_plugin_v2.py +++ b/ddtrace/contrib/internal/pytest/_plugin_v2.py @@ -181,7 +181,18 @@ def _disable_ci_visibility(): log.debug("encountered error during disable_ci_visibility", exc_info=True) +@pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_load_initial_conftests(early_config, parser, args): + """Perform early initialization of the Test Optimization plugin. + + This has to happen early enough that `sys.stderr` has not been redirected by pytest, so that logging is configured + properly. Setting the hook with `tryfirst=True` and `hookwrapper=True` achieves that. + """ + _pytest_load_initial_conftests_pre_yield(early_config, parser, args) + yield + + +def _pytest_load_initial_conftests_pre_yield(early_config, parser, args): """Performs the bare-minimum to determine whether or ModuleCodeCollector should be enabled ModuleCodeCollector has a tangible impact on the time it takes to load modules, so it should only be installed if diff --git a/ddtrace/internal/ci_visibility/utils.py b/ddtrace/internal/ci_visibility/utils.py index 770c574e98d..43cf91219e4 100644 --- a/ddtrace/internal/ci_visibility/utils.py +++ b/ddtrace/internal/ci_visibility/utils.py @@ -117,7 +117,7 @@ def take_over_logger_stream_handler(remove_ddtrace_stream_handlers=True): if remove_ddtrace_stream_handlers: log.debug("CIVisibility removing DDTrace logger handler") ddtrace_logger = logging.getLogger("ddtrace") - for handler in ddtrace_logger.handlers: + for handler in list(ddtrace_logger.handlers): ddtrace_logger.removeHandler(handler) else: log.warning("Keeping DDTrace logger handler, double logging is likely") diff --git a/releasenotes/notes/ci_visibility-fix-io-operation-closed-file-1e1089eabd5296ce.yaml b/releasenotes/notes/ci_visibility-fix-io-operation-closed-file-1e1089eabd5296ce.yaml new file mode 100644 index 00000000000..9ad2f58f3f1 --- /dev/null +++ b/releasenotes/notes/ci_visibility-fix-io-operation-closed-file-1e1089eabd5296ce.yaml @@ -0,0 +1,5 @@ +--- +fixes: + - | + CI Visibility: This fix resolves an issue where an ``I/O operation on closed file`` error was raised while printing + ``ddtrace`` logs during a pytest session, due to a conflict with pytest's log capture.