Skip to content

Commit

Permalink
Add context manager to enable python forwarding
Browse files Browse the repository at this point in the history
  • Loading branch information
timj committed Feb 5, 2019
1 parent 18e18a1 commit d49bf57
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
13 changes: 13 additions & 0 deletions python/lsst/log/log/logContinued.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,19 @@ def isEnabledFor(self, level):
return Log.getDefaultLogger().isEnabledFor(level)


class UsePythonLogging:
"""Context manager to enable Python log forwarding temporarily."""

def __init__(self):
self.current = Log.UsePythonLogging

def __enter__(self):
Log.usePythonLogging()

def __exit__(self, exc_type, exc_value, traceback):
Log.UsePythonLogging = self.current


class LogHandler(logging.Handler):
"""Handler for Python logging module that emits to LSST logging.
Expand Down
21 changes: 21 additions & 0 deletions tests/test_log.py
Original file line number Diff line number Diff line change
Expand Up @@ -602,6 +602,27 @@ def testLogLoop(self):

logging.shutdown()

def testForwardToPythonContextManager(self):
"""Test that `lsst.log` log messages can be forwarded to `logging`
using context manager"""
log.configure()

# Without forwarding we only get python logger messages captured
with self.assertLogs(level="WARNING") as cm:
log.warn("lsst.log: not forwarded")
logging.warning("Python logging: captured")
self.assertEqual(len(cm.output), 1)

# Temporarily turn on forwarding
with log.UsePythonLogging():
with self.assertLogs(level="WARNING") as cm:
log.warn("lsst.log: forwarded")
logging.warning("Python logging: also captured")
self.assertEqual(len(cm.output), 2)

# Verify that forwarding is disabled
self.assertFalse(log.Log.UsePythonLogging)


if __name__ == "__main__":
unittest.main()

0 comments on commit d49bf57

Please sign in to comment.