Base Class

MONAIPhysioBase provides the shared logging behavior used by workflow, segmentation, registration, transform, contour, and USD helper classes.

Class Reference

class monai_physio.MONAIPhysioBase(class_name=None, log_level=20, log_to_file=None)[source]

Bases: object

Base class providing standardized logging and debug settings.

This class provides a consistent logging interface for all MONAI Physio classes. All classes share a common logger called “MONAIPhysio” but include their class name in log messages for identification.

Class Attributes:

_shared_logger (logging.Logger): Shared logger for all MONAI Physio classes _class_filter (ClassNameFilter): Filter for controlling which classes show logs _logger_initialized (bool): Whether the shared logger has been set up

Instance Attributes:

class_name (str): Name of the class for log message prefixing log_level (int): Current logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)

Example

>>> import logging
>>> class MyRegistration(MONAIPhysioBase):
...     def __init__(self):
...         super().__init__(class_name='MyRegistration', log_level=logging.INFO)
...
...     def register(self):
...         self.log_info('Starting registration...')
...         self.log_debug('Using parameters: ...')
>>>
>>> # Filter to show only specific classes
>>> MONAIPhysioBase.set_log_classes(['MyRegistration'])
>>>
>>> # Show all classes again
>>> MONAIPhysioBase.set_log_all_classes()
__init__(class_name=None, log_level=20, log_to_file=None)[source]

Initialize the base class with logging configuration.

Parameters:
  • class_name (Optional[str]) – Name for the class (used in log messages). If None, uses the class name. Default: None

  • log_level (int | str) – Lowest level this object logs at. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’). set_log_level() sets a floor for every object at once. Default: logging.INFO

  • log_to_file (Optional[str]) – Optional file path to write all MONAI Physio logs to as well; only the first object’s value is used. Default: None

classmethod set_log_level(log_level)[source]

Set a floor on the logging level of every MONAI Physio object.

Each object logs at its own log_level; messages below this floor are dropped whatever that level is. Lowering the floor does not make an object log below its own log_level.

Parameters:

log_level (int | str) – Logging level. Can be an integer (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL) or a string (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).

Return type:

None

Example

>>> import logging
>>> MONAIPhysioBase.set_log_level(logging.DEBUG)
>>> # or
>>> MONAIPhysioBase.set_log_level('DEBUG')
classmethod set_log_classes(class_names)[source]

Set which classes should show their logging output.

Only log messages from the specified classes will be displayed. All other classes will have their logs hidden.

Parameters:

class_names (list[str]) – List of class names to show logs from. Example: [“RegisterModelsPCA”, “WorkflowFitStatisticalModelToPatient”]

Return type:

None

Example

>>> MONAIPhysioBase.set_log_classes(['RegisterModelsPCA'])
>>> # Now only RegisterModelsPCA logs will be shown
classmethod set_log_all_classes()[source]

Enable logging output from all MONAI Physio classes.

Disables the class filter so all classes show their logs.

Example

>>> MONAIPhysioBase.set_log_all_classes()
>>> # Now all classes will show their logs
Return type:

None

classmethod get_log_classes()[source]

Get the list of classes currently showing logs.

Return type:

list[str]

Returns:

List of class names that are allowed to show logs. Empty list if filter is disabled (all classes shown).

Example

>>> classes = MONAIPhysioBase.get_log_classes()
>>> print(classes)
['RegisterModelsPCA', 'WorkflowFitStatisticalModelToPatient']
classmethod set_progress_callback(progress_callback)[source]

Set the callback that receives progress from all MONAI Physio classes.

Like the log level, this is shared: set it once and every workflow and registrar reports to it, including those a workflow runs internally.

Each long-running method reports a fraction in [0, 1] and a short message. A workflow divides that range among its steps once, as if every optional step ran; a step that is disabled is skipped, so the fraction jumps over its share. The fraction never decreases during a run and reaches 1.0 when the run completes. Progress from runs in concurrent threads is not kept apart.

Parameters:

progress_callback (Optional[Callable[[float, str], None]]) – Receives each fraction and message, or None to stop reporting.

Return type:

None

Example

>>> def show(fraction: float, message: str) -> None:
...     print(f"{fraction:6.1%} {message}")
>>> MONAIPhysioBase.set_progress_callback(show)
>>> result = workflow.process()
log_debug(message, *args)[source]

Log a debug message with optional %-style formatting.

Parameters:
  • message (str) – The debug message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_debug('Processing %s with %d items', filename, count)
>>> self.log_debug('Value is %(value)d', {'value': 42})
log_info(message, *args)[source]

Log an info message with optional %-style formatting.

Parameters:
  • message (str) – The info message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_info('Loading file: %s', filepath)
>>> self.log_info('Iteration %(iter)d of %(total)d', {'iter': 5, 'total': 10})
log_warning(message, *args)[source]

Log a warning message with optional %-style formatting.

Parameters:
  • message (str) – The warning message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_warning('Memory usage at %d%%', usage_percent)
>>> self.log_warning('Parameter %(name)s out of range', {'name': 'threshold'})
log_error(message, *args)[source]

Log an error message with optional %-style formatting.

Parameters:
  • message (str) – The error message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_error('Failed to load %s: %s', filename, error_msg)
>>> self.log_error('Error code: %(code)d', {'code': 404})
log_critical(message, *args)[source]

Log a critical message with optional %-style formatting.

Parameters:
  • message (str) – The critical message to log (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting

Return type:

None

Example

>>> self.log_critical('System failure at %s', timestamp)
>>> self.log_critical('Critical error: %(msg)s', {'msg': 'Out of memory'})
log_section(title, *args, width=70, char='=')[source]

Log a formatted section header with optional %-style formatting.

Useful for visually separating major sections of output.

Parameters:
  • title (str) – The section title (can contain %-style placeholders)

  • *args (Any) – Arguments for %-style string formatting of title

  • width (int) – Total width of the header line. Default: 70

  • char (str) – Character to use for the header line. Default: ‘=’

Return type:

None

Example

>>> self.log_section('Stage 1: Initialization')
>>> self.log_section('Processing file: %s', filename)
>>> self.log_section('Stage %(num)d: %(name)s', {'num': 2, 'name': 'Analysis'})
# Outputs:
# ======================================================================
# Stage 2: Analysis
# ======================================================================
log_progress(current, total, prefix='Progress', *, log=True)[source]

Log progress information and report it to the progress callback.

current / total is also reported, within the current range, to the callback set by set_progress_callback().

Parameters:
  • current (int) – Current step/iteration number

  • total (int) – Total number of steps/iterations

  • prefix (str) – Prefix text for the progress message. Default: ‘Progress’

  • log (bool) – Whether to also write the progress to the log. Pass False for per-iteration progress that would flood it. Default: True

Return type:

None

Example

>>> for i in range(100):
...     self.log_progress(i + 1, 100)
>>> self.log_progress(5, 10, prefix='Processing')

Note

For custom formatted progress messages, use log_info() directly: >>> self.log_info(‘Loading %s: %d/%d’, filename, current, total)

monai_physio.ProgressCallback

Callable[[float, str], None]: called with the completed fraction in [0, 1] and a status message; see MONAIPhysioBase.set_progress_callback(). alias of Callable[[float, str], None]

Logging

Runtime classes should call log_info(), log_debug(), and log_warning() instead of printing directly. All classes share the "MONAIPhysio" logger and prefix each message with their class name.

  • Levels. Each object logs at the log_level it was created with, so a quiet registrar does not silence a verbose workflow. MONAIPhysioBase.set_log_level() sets a floor for every object at once.

  • Where messages go. If the application has configured logging before the first MONAI Physio object is created (logging.basicConfig(), 3D Slicer, most notebook setups), messages propagate to its handlers and take its format. Otherwise MONAI Physio prints them to the console itself, once.

  • Filtering. set_log_classes() shows only the named classes, wherever the messages go; set_log_all_classes() shows them all again.

import logging

from monai_physio import MONAIPhysioBase

class MyProcessor(MONAIPhysioBase):
    def __init__(self) -> None:
        super().__init__(class_name="MyProcessor", log_level=logging.INFO)

    def process(self) -> None:
        self.log_info("Starting processing")
        self.log_debug("Detailed diagnostic state")
        self.log_warning("Recoverable issue")

processor = MyProcessor()
processor.process()

MONAIPhysioBase.set_log_classes(["MyProcessor"])
MONAIPhysioBase.set_log_all_classes()

Extension Notes

New runtime classes should inherit from MONAIPhysioBase and pass a class_name plus log_level to super().__init__. Standalone scripts, data containers, and small pure utility functions do not need to inherit from the base class.

See Also