diff --git a/invesalius/gui/log.py b/invesalius/gui/log.py index 433618ac0..9f313e1b0 100644 --- a/invesalius/gui/log.py +++ b/invesalius/gui/log.py @@ -46,7 +46,8 @@ class ConsoleLogHandler(logging.StreamHandler): def __init__(self, textctrl): logging.StreamHandler.__init__(self) - formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") + #formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - (%(funcName)s) - %(message)s") + formatter = logging.Formatter("%(asctime)s - %(message)s") self.setFormatter(formatter) self.textctrl = textctrl @@ -127,7 +128,7 @@ def __init__(self): "console_logging_level": 0, "base_logging_level": logging.DEBUG, #'logging_format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s', - "logging_format": "%(asctime)s - %(levelname)s - %(message)s", + "logging_format": "%(asctime)s - %(message)s", } self.ReadConfigFile() self._logger.setLevel(self._config["base_logging_level"]) @@ -144,10 +145,10 @@ def GetConfig(self, key, default_value=None): def ReadConfigFile(self, fPath=LOG_CONFIG_PATH): try: - print(fPath, os.path.abspath(fPath)) + #print(fPath, os.path.abspath(fPath)) self._read_config_from_json(fPath) print("Reading Log config file ", fPath) - print(self._config) + #print(self._config) except Exception as e1: print("Error reading config file in ReadConfigFile:", e1) return True @@ -171,6 +172,10 @@ def getLogger(self, lname=__name__): # logger = logging.getLogger(lname) return self._logger + def formMessage(fName, className, funcName): + msg = "Hello ..." + return msg + def logMessage(self, level, msg): level = level.upper() if level == "DEBUG": @@ -190,7 +195,7 @@ def configureLogging(self): append_log_file = self._config["append_log_file"] logging_file = self._config["logging_file"] logging_file = os.path.abspath(logging_file) - print("logging_file:", logging_file) + #print("logging_file:", logging_file) console_logging = self._config["console_logging"] console_logging_level = self._config["console_logging_level"] @@ -198,27 +203,27 @@ def configureLogging(self): if (self._frame == None) & (console_logging != 0): print("Initiating console logging ...") - # self._frame = ConsoleLogFrame(self.getLogger()) - + self._frame = ConsoleLogFrame(self.getLogger()) + ''' formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s") ch = logging.StreamHandler(sys.stderr) ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) self._logger.addHandler(ch) - - print("Initiated console logging ...") + ''' + #print("Initiated console logging ...") self._logger.info("Initiated console logging ...") - msg = "file_logging: {}, console_logging: {}".format(file_logging, console_logging) - print(msg) + #msg = "file_logging: {}, console_logging: {}".format(file_logging, console_logging) + #print(msg) - self._logger.info(msg) - self._logger.info("configureLogging called ...") - self.logMessage("info", msg) + #self._logger.info(msg) + #self._logger.info("configureLogging called ...") + #self.logMessage("info", msg) if file_logging: # print('file_logging called ...') - self._logger.info("file_logging called ...") + #self._logger.info("file_logging called ...") file_logging_level = getattr( logging, const.LOGGING_LEVEL_TYPES[file_logging_level].upper(), None ) @@ -263,7 +268,7 @@ def configureLogging(self): fh.setFormatter(formatter) self._logger.addHandler(fh) - msg = "Added file handler {}".format(logging_file) + msg = "Initiated file log in {}".format(logging_file) self._logger.info(msg) else: self.closeFileLogging() @@ -285,6 +290,7 @@ def closeConsoleLogging(self): if self._frame != None: self._frame = None + def closeLogging(self): self.closeFileLogging() self.closeConsoleLogging() @@ -293,15 +299,40 @@ def flushHandlers(self): for handler in self._logger.handlers: handler.flush() - -def call_tracking_decorator(function: Callable[[str], None]): +##################################################################################### +# Decorators for logging + +def call_tracking_decorator(fileName, className, functionName=''): + def decorator(func): + def wrapper(*args, **kwargs): + invLogger._logger.debug(f"Entered File {fileName}, Class {className}, Function {functionName}" ) + func(*args, **kwargs) + return wrapper + return decorator + +def decorator_with_args(arg1, arg2): + def actual_decorator(func): + def wrapper( * args, ** kwargs): + print(f"Decorator argument 1: {arg1}") + print(f"Decorator argument 2: {arg2}") + func( * args, ** kwargs) + return wrapper + return actual_decorator + +def call_tracking_decorator00(function: Callable[[str], None]): def wrapper_accepting_arguments(*args): msg = "Function {} called".format(function.__name__) - invLogger._logger.info(msg) + invLogger._logger.debug(msg) function(*args) return wrapper_accepting_arguments +class DecorateAllMethods: + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + for attr, value in cls.__dict__.items(): + if callable(value): + setattr(cls, attr, call_tracking_decorator00(value)) ##################################################################################### # Decorators for error handling diff --git a/invesalius/gui/preferences.py b/invesalius/gui/preferences.py index ddae6e350..eff991cf8 100644 --- a/invesalius/gui/preferences.py +++ b/invesalius/gui/preferences.py @@ -303,7 +303,7 @@ def __init__(self, parent): self.Layout() - @log.call_tracking_decorator + @log.call_tracking_decorator00 def OnModifyButton(self, e): logging_file = self.tc_log_file_name.GetValue() path, fname = os.path.split(logging_file) diff --git a/invesalius/reader/bitmap_reader.py b/invesalius/reader/bitmap_reader.py index dda01bbbe..aa8ef788f 100644 --- a/invesalius/reader/bitmap_reader.py +++ b/invesalius/reader/bitmap_reader.py @@ -45,6 +45,7 @@ import invesalius.utils as utils from invesalius import inv_paths from invesalius.pubsub import pub as Publisher +import invesalius.gui.log as log # flag to control vtk error in read files no_error = True @@ -151,6 +152,7 @@ def __init__(self, bmp_file, filepath): self.run() + @log.call_tracking_decorator(os.path.basename(__file__), "LoadBitmap", "Run") def run(self): global vtk_error @@ -296,7 +298,7 @@ def VtkErrorPNGWriter(obj, f): global vtk_error vtk_error = True - +@log.call_tracking_decorator(os.path.basename(__file__), "", "ScipyRead") def ScipyRead(filepath): try: r = imread(filepath, flatten=True) @@ -312,7 +314,7 @@ def ScipyRead(filepath): except IOError: return False - +@log.call_tracking_decorator(os.path.basename(__file__), "", "VtkRead") def VtkRead(filepath, t): if not const.VTK_WARNING: log_path = os.path.join(inv_paths.USER_LOG_DIR, "vtkoutput.txt") @@ -362,7 +364,7 @@ def VtkRead(filepath, t): no_error = True return False - +@log.call_tracking_decorator(os.path.basename(__file__), "", "ReadBitmap") def ReadBitmap(filepath): t = VerifyDataType(filepath) @@ -391,7 +393,7 @@ def ReadBitmap(filepath): return img_array - +@log.call_tracking_decorator(os.path.basename(__file__), "", "GetPixelSpacingFromInfoFile") def GetPixelSpacingFromInfoFile(filepath): filepath = utils.decode(filepath, const.FS_ENCODE) diff --git a/invesalius/reader/dicom_grouper.py b/invesalius/reader/dicom_grouper.py index 82d55cef9..120ee91fa 100644 --- a/invesalius/reader/dicom_grouper.py +++ b/invesalius/reader/dicom_grouper.py @@ -1,4 +1,4 @@ -# --------------------------------------------------------------------- + # --------------------------------------------------------------------- # Software: InVesalius Software de Reconstrucao 3D de Imagens Medicas # Copyright: (c) 2001 Centro de Pesquisas Renato Archer diff --git a/invesalius/reader/dicom_reader.py b/invesalius/reader/dicom_reader.py index 1fd4f21d5..8f7bf9136 100644 --- a/invesalius/reader/dicom_reader.py +++ b/invesalius/reader/dicom_reader.py @@ -1,3 +1,4 @@ + # -------------------------------------------------------------------------- # Software: InVesalius - Software de Reconstrucao 3D de Imagens Medicas # Copyright: (C) 2001 Centro de Pesquisas Renato Archer @@ -44,6 +45,7 @@ from invesalius import inv_paths from invesalius.data import imagedata_utils from invesalius.pubsub import pub as Publisher +import invesalius.gui.log as log if sys.platform == "win32": try: @@ -113,6 +115,7 @@ def __init__(self, grouper, filepath): self.filepath = utils.decode(filepath, const.FS_ENCODE) self.run() + @log.call_tracking_decorator(os.path.basename(__file__), "LoadDicom", "Run") def run(self): grouper = self.grouper reader = gdcm.ImageReader() diff --git a/invesalius/reader/others_reader.py b/invesalius/reader/others_reader.py index 4fc5dd8ac..11d0a67af 100644 --- a/invesalius/reader/others_reader.py +++ b/invesalius/reader/others_reader.py @@ -24,8 +24,9 @@ import invesalius.constants as const from invesalius import inv_paths +import invesalius.gui.log as log - +@log.call_tracking_decorator(os.path.basename(__file__), "", "ReadOthers") def ReadOthers(dir_): """ Read the given Analyze, NIfTI, Compressed NIfTI or PAR/REC file, diff --git a/invesalius/segmentation/deep_learning/segment.py b/invesalius/segmentation/deep_learning/segment.py index 05085e370..90f622caa 100644 --- a/invesalius/segmentation/deep_learning/segment.py +++ b/invesalius/segmentation/deep_learning/segment.py @@ -16,12 +16,13 @@ from invesalius.data.converters import to_vtk from invesalius.net.utils import download_url_to_file from invesalius.utils import new_name_by_pattern +import invesalius.gui.log as log from . import utils SIZE = 48 - +@log.call_tracking_decorator(os.path.basename(__file__), "", "gen_patches") def gen_patches(image, patch_size, overlap): overlap = int(patch_size * overlap / 100) sz, sy, sx = image.shape @@ -45,6 +46,7 @@ def gen_patches(image, patch_size, overlap): yield (idx + 1.0) / len(i_cuts), sub_image, ((iz, ez), (iy, ey), (ix, ex)) +@log.call_tracking_decorator(os.path.basename(__file__), "", "predict_patch") def predict_patch(sub_image, patch, nn_model, patch_size): (iz, ez), (iy, ey), (ix, ex) = patch sub_mask = nn_model.predict(sub_image.reshape(1, patch_size, patch_size, patch_size, 1)) @@ -53,6 +55,7 @@ def predict_patch(sub_image, patch, nn_model, patch_size): ] +@log.call_tracking_decorator(os.path.basename(__file__), "", "predict_patch") def predict_patch_torch(sub_image, patch, nn_model, device, patch_size): import torch @@ -72,6 +75,7 @@ def predict_patch_torch(sub_image, patch, nn_model, device, patch_size): ] +@log.call_tracking_decorator(os.path.basename(__file__), "", "predict_patch") def segment_keras(image, weights_file, overlap, probability_array, comm_array, patch_size): import keras @@ -102,6 +106,7 @@ def _download_callback(value): return _download_callback +@log.call_tracking_decorator(os.path.basename(__file__), "", "segment_torch") def segment_torch( image, weights_file, overlap, device_id, probability_array, comm_array, patch_size ): @@ -134,6 +139,7 @@ def segment_torch( comm_array[0] = np.Inf +@log.call_tracking_decorator(os.path.basename(__file__), "", "segment_torch_jit") def segment_torch_jit( image, weights_file, @@ -256,6 +262,7 @@ def __init__( self.mask = None + @log.call_tracking_decorator(os.path.basename(__file__), "SegmentProcess", "run") def run(self): try: self._run_segmentation()