# MIT License
# Copyright (c) 2025 aeeeeeep
import logging
from types import ModuleType
from typing import Optional, Union, List, Any
from .config import ObjWatchConfig
from .tracer import Tracer
from .wrappers import ABCWrapper
from .utils.logger import create_logger, log_info
from .runtime_info import runtime_info
[docs]
class ObjWatch:
"""
Tracing and logging of specified Python modules to aid in debugging and monitoring.
"""
[docs]
def __init__(
self,
targets: List[Union[str, ModuleType]],
exclude_targets: Optional[List[Union[str, ModuleType]]] = None,
with_locals: bool = False,
with_globals: bool = False,
output: Optional[str] = None,
output_json: Optional[str] = None,
level: int = logging.DEBUG,
simple: bool = True,
wrapper: Optional[ABCWrapper] = None,
framework: Optional[str] = None,
indexes: Optional[List[int]] = None,
) -> None:
"""
Initialize the ObjWatch instance with configuration parameters.
Args:
targets (List[Union[str, ModuleType]]): Files or modules to monitor.
exclude_targets (Optional[List[Union[str, ModuleType]]]): Files or modules to exclude from monitoring.
with_locals (bool): Enable tracing and logging of local variables within functions.
with_globals (bool): Enable tracing and logging of global variables across function calls.
output (Optional[str]): File path for writing logs, must end with '.objwatch' for ObjWatch Log Viewer extension.
output_json (Optional[str]): JSON file path for writing structured logs.
level (int): Logging level (e.g., logging.DEBUG, logging.INFO).
simple (bool): Defaults to True, disable simple logging mode with the format "[{time}] [{level}] objwatch: {msg}".
wrapper (Optional[ABCWrapper]): Custom wrapper to extend tracing and logging functionality.
framework (Optional[str]): The multi-process framework module to use.
indexes (Optional[List[int]]): The indexes to track in a multi-process environment.
"""
# Create configuration parameters for ObjWatch
config = ObjWatchConfig(**{k: v for k, v in locals().items() if k != 'self'})
# Create and configure the logger based on provided parameters
create_logger(output=config.output, level=config.level, simple=config.simple)
# Initialize the Tracer with the given configuration
self.tracer = Tracer(config=config)
[docs]
def start(self) -> None:
"""
Start the ObjWatch tracing process.
"""
log_info("Starting ObjWatch tracing.")
runtime_info.update()
self.tracer.start()
[docs]
def stop(self) -> None:
"""
Stop the ObjWatch tracing process.
"""
log_info("Stopping ObjWatch tracing.")
self.tracer.stop()
[docs]
def __enter__(self) -> 'ObjWatch':
"""
Enter the runtime context related to this object.
Returns:
ObjWatch: The ObjWatch instance itself.
"""
self.start()
return self
[docs]
def __exit__(self, exc_type: Optional[type], exc_val: Optional[BaseException], exc_tb: Optional[Any]) -> None:
"""
Exit the runtime context and stop tracing.
Args:
exc_type (Optional[type]): The exception type.
exc_val (Optional[BaseException]): The exception value.
exc_tb (Optional[Any]): The traceback object.
"""
self.stop()
[docs]
def watch(
targets: List[Union[str, ModuleType]],
exclude_targets: Optional[List[Union[str, ModuleType]]] = None,
with_locals: bool = False,
with_globals: bool = False,
output: Optional[str] = None,
output_json: Optional[str] = None,
level: int = logging.DEBUG,
simple: bool = True,
wrapper: Optional[ABCWrapper] = None,
framework: Optional[str] = None,
indexes: Optional[List[int]] = None,
) -> ObjWatch:
"""
Initialize and start an ObjWatch instance.
Args:
targets (List[Union[str, ModuleType]]): Files or modules to monitor.
exclude_targets (Optional[List[Union[str, ModuleType]]]): Files or modules to exclude from monitoring.
with_locals (bool): Enable tracing and logging of local variables within functions.
with_globals (bool): Enable tracing and logging of global variables across function calls.
output (Optional[str]): File path for writing logs, must end with '.objwatch' for ObjWatch Log Viewer extension.
output_json (Optional[str]): JSON file path for writing structured logs.
level (int): Logging level (e.g., logging.DEBUG, logging.INFO).
simple (bool): Defaults to True, disable simple logging mode with the format "[{time}] [{level}] objwatch: {msg}".
wrapper (Optional[ABCWrapper]): Custom wrapper to extend tracing and logging functionality.
framework (Optional[str]): The multi-process framework module to use.
indexes (Optional[List[int]]): The indexes to track in a multi-process environment.
Returns:
ObjWatch: The initialized and started ObjWatch instance.
"""
# Instantiate the ObjWatch with the provided configuration
obj_watch = ObjWatch(**locals())
# Start the tracing process
obj_watch.start()
return obj_watch