Skip to content

Commit 37c0f9c

Browse files
authored
gh-95804: Respect MemoryHandler.flushOnClose in logging shutdown. (GH-95857)
1 parent 71c3d64 commit 37c0f9c

File tree

4 files changed

+37
-1
lines changed

4 files changed

+37
-1
lines changed

Lib/logging/__init__.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2245,7 +2245,11 @@ def shutdown(handlerList=_handlerList):
22452245
if h:
22462246
try:
22472247
h.acquire()
2248-
h.flush()
2248+
# MemoryHandlers might not want to be flushed on close,
2249+
# but circular imports prevent us scoping this to just
2250+
# those handlers. hence the default to True.
2251+
if getattr(h, 'flushOnClose', True):
2252+
h.flush()
22492253
h.close()
22502254
except (OSError, ValueError):
22512255
# Ignore errors which might be caused

Lib/test/test_logging.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1225,6 +1225,35 @@ def test_flush_on_close(self):
12251225
# assert that no new lines have been added
12261226
self.assert_log_lines(lines) # no change
12271227

1228+
def test_shutdown_flush_on_close(self):
1229+
"""
1230+
Test that the flush-on-close configuration is respected by the
1231+
shutdown method.
1232+
"""
1233+
self.mem_logger.debug(self.next_message())
1234+
self.assert_log_lines([])
1235+
self.mem_logger.info(self.next_message())
1236+
self.assert_log_lines([])
1237+
# Default behaviour is to flush on close. Check that it happens.
1238+
logging.shutdown(handlerList=[logging.weakref.ref(self.mem_hdlr)])
1239+
lines = [
1240+
('DEBUG', '1'),
1241+
('INFO', '2'),
1242+
]
1243+
self.assert_log_lines(lines)
1244+
# Now configure for flushing not to be done on close.
1245+
self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING,
1246+
self.root_hdlr,
1247+
False)
1248+
self.mem_logger.addHandler(self.mem_hdlr)
1249+
self.mem_logger.debug(self.next_message())
1250+
self.assert_log_lines(lines) # no change
1251+
self.mem_logger.info(self.next_message())
1252+
self.assert_log_lines(lines) # no change
1253+
# assert that no new lines have been added after shutdown
1254+
logging.shutdown(handlerList=[logging.weakref.ref(self.mem_hdlr)])
1255+
self.assert_log_lines(lines) # no change
1256+
12281257
@threading_helper.requires_working_threading()
12291258
def test_race_between_set_target_and_flush(self):
12301259
class MockRaceConditionHandler:

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ Gawain Bolton
198198
Carl Friedrich Bolz-Tereick
199199
Forest Bond
200200
Gregory Bond
201+
David Bonner
201202
Angelin Booz
202203
Médéric Boquien
203204
Matias Bordese
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix ``logging`` shutdown handler so it respects
2+
``MemoryHandler.flushOnClose``.

0 commit comments

Comments
 (0)