summaryrefslogtreecommitdiff
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rw-r--r--Lib/logging/__init__.py20
-rw-r--r--Lib/test/test_logging.py14
2 files changed, 34 insertions, 0 deletions
diff --git a/Lib/logging/__init__.py b/Lib/logging/__init__.py
index f9bfb79ae6..54d4e883d9 100644
--- a/Lib/logging/__init__.py
+++ b/Lib/logging/__init__.py
@@ -997,6 +997,26 @@ class StreamHandler(Handler):
except Exception:
self.handleError(record)
+ def setStream(self, stream):
+ """
+ Sets the StreamHandler's stream to the specified value,
+ if it is different.
+
+ Returns the old stream, if the stream was changed, or None
+ if it wasn't.
+ """
+ if stream is self.stream:
+ result = None
+ else:
+ result = self.stream
+ self.acquire()
+ try:
+ self.flush()
+ self.stream = stream
+ finally:
+ self.release()
+ return result
+
def __repr__(self):
level = getLevelName(self.level)
name = getattr(self.stream, 'name', '')
diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py
index 8884562961..6d0b23441b 100644
--- a/Lib/test/test_logging.py
+++ b/Lib/test/test_logging.py
@@ -698,6 +698,20 @@ class StreamHandlerTest(BaseTest):
finally:
logging.raiseExceptions = old_raise
+ def test_stream_setting(self):
+ """
+ Test setting the handler's stream
+ """
+ h = logging.StreamHandler()
+ stream = io.StringIO()
+ old = h.setStream(stream)
+ self.assertIs(old, sys.stderr)
+ actual = h.setStream(old)
+ self.assertIs(actual, stream)
+ # test that setting to existing value returns None
+ actual = h.setStream(old)
+ self.assertIsNone(actual)
+
# -- The following section could be moved into a server_helper.py module
# -- if it proves to be of wider utility than just test_logging