Skip to content

Commit

Permalink
logging: close log_file_handler
Browse files Browse the repository at this point in the history
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
  • Loading branch information
blueyed committed Mar 26, 2019
1 parent 4148663 commit 61e7608
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/4988.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Close logging's file handler explicitly when the session finishes.
3 changes: 3 additions & 0 deletions src/_pytest/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -579,6 +579,9 @@ def pytest_sessionfinish(self):
if self.log_file_handler is not None:
with catching_logs(self.log_file_handler, level=self.log_file_level):
yield
# Close the FileHandler explicitly.
# (logging.shutdown might have lost the weakref?!)
self.log_file_handler.close()
else:
yield

Expand Down

0 comments on commit 61e7608

Please sign in to comment.