Skip to content

Commit

Permalink
pythongh-127567: Avoid shuting down handlers during reconfiguration
Browse files Browse the repository at this point in the history
  • Loading branch information
Agent-Hellboy committed Dec 6, 2024
1 parent 8b3cccf commit 410909f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
15 changes: 13 additions & 2 deletions Lib/logging/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,9 +285,20 @@ def _install_loggers(cp, handlers, disable_existing):


def _clearExistingHandlers():
"""Clear and close existing handlers"""
"""Clear and close handlers that are no longer in use."""
active_handlers = {
handler
for logger in logging.Logger.manager.loggerDict.values()
if isinstance(logger, logging.Logger)
for handler in logger.handlers
}

for handler_ref in list(logging._handlers.values()):
handler = handler_ref() if callable(handler_ref) else handler_ref
if handler and handler not in active_handlers:
handler.close()

logging._handlers.clear()
logging.shutdown(logging._handlerList[:])
del logging._handlerList[:]


Expand Down
26 changes: 26 additions & 0 deletions Lib/test/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -3554,6 +3554,32 @@ def test_config15_ok(self):
handler = logging.root.handlers[0]
self.addCleanup(closeFileHandler, handler, fn)

def test_clear_existing_handlers_preserves_active_handlers(self):
"""Test that active handlers are preserved and unused handlers are closed."""

with self.check_no_resource_warning():
fn = make_temp_file(".log", "test_logging-clear-")
config = {
"version": 1,
"handlers": {
"file": {
"class": "logging.FileHandler",
"filename": fn,
"encoding": "utf-8",
}
},
"root": {
"handlers": ["file"]
}
}

self.apply_config(config)
self.apply_config(config)

handler = logging.root.handlers[0]
self.assertFalse(handler._closed, "Handler should not be closed")
self.addCleanup(closeFileHandler, handler, fn)

def test_config16_ok(self):
self.apply_config(self.config16)
h = logging._handlers['hand1']
Expand Down

0 comments on commit 410909f

Please sign in to comment.