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: c1419578a1/Lib/logging/__init__.py (L2107-L2139)
This commit is contained in:
Daniel Hahler 2019-03-23 09:16:14 +01:00
parent ee96214a8d
commit 538efef1ba
2 changed files with 10 additions and 2 deletions

View File

@ -0,0 +1 @@
Close logging's file handler explicitly when the session finishes.

View File

@ -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