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 import SimpleITK as sitk
20 import logging
21 import os
22 
23 
24 class SimpleITKLogger(sitk.LoggerBase):
25  """
26  Adapts SimpleITK messages to be handled by a Python Logger object.
27 
28  Allows using the logging module to control the handling of messages coming
29  from ITK and SimpleTK. Messages such as debug and warnings are handled by
30  objects derived from sitk.LoggerBase.
31 
32  The LoggerBase.SetAsGlobalITKLogger method must be called to enable
33  SimpleITK messages to use the logger.
34 
35  The Python logger module adds a second layer of control for the logging
36  level in addition to the controls already in SimpleITK.
37 
38  The "Debug" property of a SimpleITK object must be enabled (if
39  available) and the support from the Python "logging flow" hierarchy
40  to handle debug messages from a SimpleITK object.
41 
42  Warning messages from SimpleITK are globally disabled with
43  ProcessObject:GlobalWarningDisplayOff.
44  """
45 
46  def __init__(
47  self, logger: logging.Logger = logging.getLogger("SimpleITK")
48  ):
49  """
50  Initializes with a Logger object to handle the messages emitted from
51  SimpleITK/ITK.
52  """
53  super(SimpleITKLogger, self).__init__()
54  self._logger = logger
55 
56  @property
57  def logger(self):
58  return self._logger
59 
60  @logger.setter
61  def logger(self, logger):
62  self._logger = logger
63 
64  def __enter__(self):
65  self._old_logger = self.SetAsGlobalITKLogger()
66  return self
67 
68  def __exit__(self, exc_type, exc_val, exc_tb):
69  self._old_logger.SetAsGlobalITKLogger()
70  del self._old_logger
71 
72  def DisplayText(self, s):
73  # Remove newline endings from SimpleITK/ITK messages since the Python
74  # logger adds during output.
75  self._logger.info(s.rstrip())
76 
77  def DisplayErrorText(self, s):
78  self._logger.error(s.rstrip())
79 
80  def DisplayWarningText(self, s):
81  self._logger.warning(s.rstrip())
82 
83  def DisplayGenericOutputText(self, s):
84  self._logger.info(s.rstrip())
85 
86  def DisplayDebugText(self, s):
87  self._logger.debug(s.rstrip())
88 
89 
90 # Enable all debug messages for all ProcessObjects, and procedures
91 sitk.ProcessObject.GlobalDefaultDebugOn()
92 
93 # Construct a SimpleITK logger to Python Logger adaptor
94 sitkLogger = SimpleITKLogger()
95 
96 # Configure ITK to use the logger adaptor
97 sitkLogger.SetAsGlobalITKLogger()
98 
99 # Configure the Python root logger, enabling debug and info level messages.
100 logging.basicConfig(
101  format="%(name)s (%(levelname)s): %(message)s", level=logging.DEBUG
102 )
103 
104 
105 img = sitk.GaborSource(size=[64, 64, 64], frequency=4.0 / 64)
106 
107 with SimpleITKLogger(logging.getLogger("Show")) as showLogger:
108  print(f"Logger name: {showLogger.GetName()}")
109 
110  if "SITK_NOSHOW" not in os.environ:
111  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.