From 538efef1baafff948ad43bf7adeae62c2dfc88bc Mon Sep 17 00:00:00 2001 From: Daniel Hahler Date: Sat, 23 Mar 2019 09:16:14 +0100 Subject: [PATCH] logging: close log_file_handler While it should be closed in logging's shutdown [1], the following would still issue a ResourceWarning: ``` import logging log_file_handler = logging.FileHandler("temp.log", mode="w", encoding="UTF-8") root_logger = logging.getLogger() root_logger.addHandler(log_file_handler) root_logger.removeHandler(log_file_handler) root_logger.error("error") del log_file_handler ``` It looks like the weakref might get lost for some reason. See https://github.com/pytest-dev/pytest/pull/4981/commits/92ffe42b45 / #4981 for more information. 1: https://github.com/python/cpython/blob/c1419578a18d787393c7ccee149e7c1fff17a99e/Lib/logging/__init__.py#L2107-L2139 --- changelog/4988.bugfix.rst | 1 + src/_pytest/logging.py | 11 +++++++++-- 2 files changed, 10 insertions(+), 2 deletions(-) create mode 100644 changelog/4988.bugfix.rst diff --git a/changelog/4988.bugfix.rst b/changelog/4988.bugfix.rst new file mode 100644 index 000000000..8cc816ed6 --- /dev/null +++ b/changelog/4988.bugfix.rst @@ -0,0 +1 @@ +Close logging's file handler explicitly when the session finishes. diff --git a/src/_pytest/logging.py b/src/_pytest/logging.py index 22db44301..5a31dfc5c 100644 --- a/src/_pytest/logging.py +++ b/src/_pytest/logging.py @@ -577,8 +577,15 @@ class LoggingPlugin(object): if self.log_cli_handler: self.log_cli_handler.set_when("sessionfinish") if self.log_file_handler is not None: - with catching_logs(self.log_file_handler, level=self.log_file_level): - yield + try: + with catching_logs( + self.log_file_handler, level=self.log_file_level + ): + yield + finally: + # Close the FileHandler explicitly. + # (logging.shutdown might have lost the weakref?!) + self.log_file_handler.close() else: yield