Skip to content

Commit

Permalink
bpo-41503: Fix race between setTarget and flush in logging.handlers.M…
Browse files Browse the repository at this point in the history
…emoryHandler (pythonGH-21765)
  • Loading branch information
iritkatriel authored Aug 16, 2020
1 parent fff3c28 commit 2353d77
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
6 changes: 5 additions & 1 deletion Lib/logging/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -1324,7 +1324,11 @@ def setTarget(self, target):
"""
Set the target handler for this handler.
"""
self.target = target
self.acquire()
try:
self.target = target
finally:
self.release()

def flush(self):
"""
Expand Down
21 changes: 21 additions & 0 deletions Lib/test/test_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,27 @@ def test_flush_on_close(self):
# assert that no new lines have been added
self.assert_log_lines(lines) # no change

def test_race_between_set_target_and_flush(self):
class MockRaceConditionHandler:
def __init__(self, mem_hdlr):
self.mem_hdlr = mem_hdlr

def removeTarget(self):
self.mem_hdlr.setTarget(None)

def handle(self, msg):
t = threading.Thread(target=self.removeTarget)
t.daemon = True
t.start()

target = MockRaceConditionHandler(self.mem_hdlr)
self.mem_hdlr.setTarget(target)

for _ in range(10):
time.sleep(0.005)
self.mem_logger.info("not flushed")
self.mem_logger.warning("flushed")


class ExceptionFormatter(logging.Formatter):
"""A special exception formatter."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed a race between setTarget and flush in logging.handlers.MemoryHandler.

0 comments on commit 2353d77

Please sign in to comment.