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