Skip to content

Commit 538efef

Browse files
committed
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 92ffe42b45 / #4981 for more information. 1: https://github.com/python/cpython/blob/c1419578a18d787393c7ccee149e7c1fff17a99e/Lib/logging/__init__.py#L2107-L2139
1 parent ee96214 commit 538efef

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

changelog/4988.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Close logging's file handler explicitly when the session finishes.

src/_pytest/logging.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -577,8 +577,15 @@ def pytest_sessionfinish(self):
577577
if self.log_cli_handler:
578578
self.log_cli_handler.set_when("sessionfinish")
579579
if self.log_file_handler is not None:
580-
with catching_logs(self.log_file_handler, level=self.log_file_level):
581-
yield
580+
try:
581+
with catching_logs(
582+
self.log_file_handler, level=self.log_file_level
583+
):
584+
yield
585+
finally:
586+
# Close the FileHandler explicitly.
587+
# (logging.shutdown might have lost the weakref?!)
588+
self.log_file_handler.close()
582589
else:
583590
yield
584591

0 commit comments

Comments
 (0)