19 """ A SimpleITK example that demonstrates how to adapt SimpleITK messages
20 to be handled by a Python Logger object. """
24 import SimpleITK
as sitk
29 Adapts SimpleITK messages to be handled by a Python Logger object.
31 Allows using the logging module to control the handling of messages coming
32 from ITK and SimpleTK. Messages such as debug and warnings are handled by
33 objects derived from sitk.LoggerBase.
35 The LoggerBase.SetAsGlobalITKLogger method must be called to enable
36 SimpleITK messages to use the logger.
38 The Python logger module adds a second layer of control for the logging
39 level in addition to the controls already in SimpleITK.
41 The "Debug" property of a SimpleITK object must be enabled (if
42 available) and the support from the Python "logging flow" hierarchy
43 to handle debug messages from a SimpleITK object.
45 Warning messages from SimpleITK are globally disabled with
46 ProcessObject:GlobalWarningDisplayOff.
49 def __init__(self, logger: logging.Logger = logging.getLogger(
"SimpleITK")):
51 Initializes with a Logger object to handle the messages emitted from
59 """ return the logger object """
63 def logger(self, logger):
64 """ set the logger object """
68 """ Set this object as the global ITK logger. """
69 self._old_logger = self.SetAsGlobalITKLogger()
72 def __exit__(self, exc_type, exc_val, exc_tb):
73 """ Restore the previous global ITK logger. """
74 self._old_logger.SetAsGlobalITKLogger()
77 def DisplayText(self, s):
78 """ Display text message. """
81 self._logger.info(s.rstrip())
83 def DisplayErrorText(self, s):
84 self._logger.error(s.rstrip())
86 def DisplayWarningText(self, s):
87 self._logger.warning(s.rstrip())
89 def DisplayGenericOutputText(self, s):
90 self._logger.info(s.rstrip())
92 def DisplayDebugText(self, s):
93 self._logger.debug(s.rstrip())
97 sitk.ProcessObject.GlobalDefaultDebugOn()
100 sitkLogger = SimpleITKLogger()
103 sitkLogger.SetAsGlobalITKLogger()
106 logging.basicConfig(format=
"%(name)s (%(levelname)s): %(message)s", level=logging.DEBUG)
111 with SimpleITKLogger(logging.getLogger(
"Show"))
as showLogger:
112 print(f
"Logger name: {showLogger.GetName()}")
114 if "SITK_NOSHOW" not in os.environ: