SimpleITK  
Logging/Logging.py
1 # =========================================================================
2 #
3 # Copyright NumFOCUS
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0.txt
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 # =========================================================================
18 
19 """ A SimpleITK example that demonstrates how to adapt SimpleITK messages
20  to be handled by a Python Logger object. """
21 
22 import logging
23 import os
24 import SimpleITK as sitk
25 
26 
27 class SimpleITKLogger(sitk.LoggerBase):
28  """
29  Adapts SimpleITK messages to be handled by a Python Logger object.
30 
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.
34 
35  The LoggerBase.SetAsGlobalITKLogger method must be called to enable
36  SimpleITK messages to use the logger.
37 
38  The Python logger module adds a second layer of control for the logging
39  level in addition to the controls already in SimpleITK.
40 
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.
44 
45  Warning messages from SimpleITK are globally disabled with
46  ProcessObject:GlobalWarningDisplayOff.
47  """
48 
49  def __init__(self, logger: logging.Logger = logging.getLogger("SimpleITK")):
50  """
51  Initializes with a Logger object to handle the messages emitted from
52  SimpleITK/ITK.
53  """
54  super().__init__()
55  self._logger = logger
56 
57  @property
58  def logger(self):
59  """ return the logger object """
60  return self._logger
61 
62  @logger.setter
63  def logger(self, logger):
64  """ set the logger object """
65  self._logger = logger
66 
67  def __enter__(self):
68  """ Set this object as the global ITK logger. """
69  self._old_logger = self.SetAsGlobalITKLogger()
70  return self
71 
72  def __exit__(self, exc_type, exc_val, exc_tb):
73  """ Restore the previous global ITK logger. """
74  self._old_logger.SetAsGlobalITKLogger()
75  del self._old_logger
76 
77  def DisplayText(self, s):
78  """ Display text message. """
79  # Remove newline endings from SimpleITK/ITK messages since the Python
80  # logger adds during output.
81  self._logger.info(s.rstrip())
82 
83  def DisplayErrorText(self, s):
84  self._logger.error(s.rstrip())
85 
86  def DisplayWarningText(self, s):
87  self._logger.warning(s.rstrip())
88 
89  def DisplayGenericOutputText(self, s):
90  self._logger.info(s.rstrip())
91 
92  def DisplayDebugText(self, s):
93  self._logger.debug(s.rstrip())
94 
95 
96 # Enable all debug messages for all ProcessObjects, and procedures
97 sitk.ProcessObject.GlobalDefaultDebugOn()
98 
99 # Construct a SimpleITK logger to Python Logger adaptor
100 sitkLogger = SimpleITKLogger()
101 
102 # Configure ITK to use the logger adaptor
103 sitkLogger.SetAsGlobalITKLogger()
104 
105 # Configure the Python root logger, enabling debug and info level messages.
106 logging.basicConfig(format="%(name)s (%(levelname)s): %(message)s", level=logging.DEBUG)
107 
108 
109 img = sitk.GaborSource(size=[64, 64, 64], frequency=4.0 / 64)
110 
111 with SimpleITKLogger(logging.getLogger("Show")) as showLogger:
112  print(f"Logger name: {showLogger.GetName()}")
113 
114  if "SITK_NOSHOW" not in os.environ:
115  sitk.Show(img, debugOn=True)
itk::simple::Show
void SITKIO_EXPORT Show(const Image &image, const std::string &title="", const bool debugOn=ProcessObject::GetGlobalDefaultDebug())
itk::simple::LoggerBase
A base class to handle SimpleITK and ITK messages and logging.
Definition: sitkLogger.h:48
itk::simple::GaborSource
Image GaborSource(PixelIDValueEnum outputPixelType=itk::simple::sitkFloat32, std::vector< unsigned int > size=std::vector< unsigned int >(3, 64), std::vector< double > sigma=std::vector< double >(3, 16.0), std::vector< double > mean=std::vector< double >(3, 32.0), double frequency=0.4, std::vector< double > origin=std::vector< double >(3, 0.0), std::vector< double > spacing=std::vector< double >(3, 1.0), std::vector< double > direction=std::vector< double >())
Generate an n-dimensional image of a Gabor filter.