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__(self, logger: logging.Logger = logging.getLogger("SimpleITK")):
47  """
48  Initializes with a Logger object to handle the messages emitted from
49  SimpleITK/ITK.
50  """
51  super(SimpleITKLogger, self).__init__()
52  self._logger = logger
53 
54  @property
55  def logger(self):
56  return self._logger
57 
58  @logger.setter
59  def logger(self, logger):
60  self._logger = logger
61 
62  def __enter__(self):
63  self._old_logger = self.SetAsGlobalITKLogger()
64  return self
65 
66  def __exit__(self, exc_type, exc_val, exc_tb):
67  self._old_logger.SetAsGlobalITKLogger()
68  del self._old_logger
69 
70  def DisplayText(self, s):
71  # Remove newline endings from SimpleITK/ITK messages since the Python
72  # logger adds during output.
73  self._logger.info(s.rstrip())
74 
75  def DisplayErrorText(self, s):
76  self._logger.error(s.rstrip())
77 
78  def DisplayWarningText(self, s):
79  self._logger.warning(s.rstrip())
80 
81  def DisplayGenericOutputText(self, s):
82  self._logger.info(s.rstrip())
83 
84  def DisplayDebugText(self, s):
85  self._logger.debug(s.rstrip())
86 
87 
88 # Enable all debug messages for all ProcessObjects, and procedures
89 sitk.ProcessObject.GlobalDefaultDebugOn()
90 
91 # Construct a SimpleITK logger to Python Logger adaptor
92 sitkLogger = SimpleITKLogger()
93 
94 # Configure ITK to use the logger adaptor
95 sitkLogger.SetAsGlobalITKLogger()
96 
97 # Configure the Python root logger, enabling debug and info level messages.
98 logging.basicConfig(format="%(name)s (%(levelname)s): %(message)s", level=logging.DEBUG)
99 
100 
101 img = sitk.GaborSource(size=[64, 64, 64], frequency=4.0 / 64)
102 
103 with SimpleITKLogger(logging.getLogger("Show")) as showLogger:
104  print(f"Logger name: {showLogger.GetName()}")
105 
106  if "SITK_NOSHOW" not in os.environ:
107  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.