Skip to content

pygx.instrument.logging

Logging for PyGX.

logging

Logging for PyGX.

This module allows PyGX to use an externally created logger for logging PyGX events without introducing library dependencies in PyGX.

register_frame_to_skip

register_frame_to_skip(
    method: Callable[..., Any] | list[Callable[..., Any]],
) -> bool

Registers the source of the given method to be skipped when logging.

Only has an effect when the current logger's class supports frame skipping (i.e. exposes a register_frame_to_skip method).

Parameters:

Name Type Description Default
method Callable[..., Any] | list[Callable[..., Any]]

The method to skip. Can be a single method or a list of methods.

required

Returns:

Type Description
bool

True if the method is registered to skip; False if the current logger

bool

class does not support frame skipping.

Raises:

Type Description
TypeError

The source file of the method cannot be inspected.

Source code in pygx/instrument/_logging.py
def register_frame_to_skip(
    method: Callable[..., Any] | list[Callable[..., Any]],
) -> bool:
    """Registers the source of the given method to be skipped when logging.

    Only has an effect when the current logger's class supports frame
    skipping (i.e. exposes a ``register_frame_to_skip`` method).

    Args:
      method: The method to skip. Can be a single method or a list of
        methods.

    Returns:
      True if the method is registered to skip; False if the current logger
      class does not support frame skipping.

    Raises:
      TypeError: The source file of the method cannot be inspected.
    """
    register_fn = getattr(
        _DEFAULT_LOGGER.__class__, 'register_frame_to_skip', None
    )
    if register_fn is None:
        return False
    methods = [method] if not isinstance(method, list) else method
    for m in methods:
        register_fn(inspect.getsourcefile(m), m.__name__)
    return True

set_logger

set_logger(logger: Logger) -> None

Sets current logger.

Source code in pygx/instrument/_logging.py
def set_logger(logger: logging.Logger) -> None:
    """Sets current logger."""
    global _DEFAULT_LOGGER  # pylint: disable=global-statement
    _DEFAULT_LOGGER = logger

    # Skip logging frames in pygx.instrument.logging.
    register_frame_to_skip([debug, info, warning, error, critical])

get_logger

get_logger() -> Logger

Gets the current logger.

Source code in pygx/instrument/_logging.py
def get_logger() -> logging.Logger:
    """Gets the current logger."""
    return _DEFAULT_LOGGER

debug

debug(msg: str, *args: Any, **kwargs: Any) -> None

Logs debug message.

Parameters:

Name Type Description Default
msg str

Message with possible format string.

required
*args Any

Values for variables in the format string.

()
**kwargs Any

Keyword arguments for the logger.

{}
Source code in pygx/instrument/_logging.py
def debug(msg: str, *args: Any, **kwargs: Any) -> None:
    """Logs debug message.

    Args:
      msg: Message with possible format string.
      *args: Values for variables in the format string.
      **kwargs: Keyword arguments for the logger.
    """
    _DEFAULT_LOGGER.debug(msg, *args, **kwargs)

info

info(msg: str, *args: Any, **kwargs: Any) -> None

Logs info message.

Parameters:

Name Type Description Default
msg str

Message with possible format string.

required
*args Any

Values for variables in the format string.

()
**kwargs Any

Keyword arguments for the logger.

{}
Source code in pygx/instrument/_logging.py
def info(msg: str, *args: Any, **kwargs: Any) -> None:
    """Logs info message.

    Args:
      msg: Message with possible format string.
      *args: Values for variables in the format string.
      **kwargs: Keyword arguments for the logger.
    """
    _DEFAULT_LOGGER.info(msg, *args, **kwargs)

warning

warning(msg: str, *args: Any, **kwargs: Any) -> None

Logs warning message.

Parameters:

Name Type Description Default
msg str

Message with possible format string.

required
*args Any

Values for variables in the format string.

()
**kwargs Any

Keyword arguments for the logger.

{}
Source code in pygx/instrument/_logging.py
def warning(msg: str, *args: Any, **kwargs: Any) -> None:
    """Logs warning message.

    Args:
      msg: Message with possible format string.
      *args: Values for variables in the format string.
      **kwargs: Keyword arguments for the logger.
    """
    _DEFAULT_LOGGER.warning(msg, *args, **kwargs)

error

error(msg: str, *args: Any, **kwargs: Any) -> None

Logs error message.

Parameters:

Name Type Description Default
msg str

Message with possible format string.

required
*args Any

Values for variables in the format string.

()
**kwargs Any

Keyword arguments for the logger.

{}
Source code in pygx/instrument/_logging.py
def error(msg: str, *args: Any, **kwargs: Any) -> None:
    """Logs error message.

    Args:
      msg: Message with possible format string.
      *args: Values for variables in the format string.
      **kwargs: Keyword arguments for the logger.
    """
    _DEFAULT_LOGGER.error(msg, *args, **kwargs)

critical

critical(msg: str, *args: Any, **kwargs: Any) -> None

Logs critical message.

Parameters:

Name Type Description Default
msg str

Message with possible format string.

required
*args Any

Values for variables in the format string.

()
**kwargs Any

Keyword arguments for the logger.

{}
Source code in pygx/instrument/_logging.py
def critical(msg: str, *args: Any, **kwargs: Any) -> None:
    """Logs critical message.

    Args:
      msg: Message with possible format string.
      *args: Values for variables in the format string.
      **kwargs: Keyword arguments for the logger.
    """
    _DEFAULT_LOGGER.critical(msg, *args, **kwargs)

use_stream

use_stream(
    stream: Any,
    level: int = INFO,
    name: str = "custom",
    fmt: str = "{levelname:8} | {asctime} | {message}",
    datefmt: str = "%Y-%m-%d %H:%M:%S",
) -> Logger

Uses the given stream for logging and installs it as current logger.

Source code in pygx/instrument/_logging.py
def use_stream(
    stream: Any,
    level: int = logging.INFO,
    name: str = 'custom',
    fmt: str = '{levelname:8} | {asctime} | {message}',
    datefmt: str = '%Y-%m-%d %H:%M:%S',
) -> logging.Logger:
    """Uses the given stream for logging and installs it as current logger."""
    logger = logging.getLogger(name)
    logger.setLevel(level)
    stdout_handler = logging.StreamHandler(stream=stream)
    stdout_handler.setLevel(level)
    stdout_handler.setFormatter(
        logging.Formatter(fmt=fmt, datefmt=datefmt, style='{')
    )
    logger.addHandler(stdout_handler)
    set_logger(logger)
    return logger

use_stdout

use_stdout(
    level: int = INFO,
    fmt: str = "{levelname:8} | {asctime} | {message}",
    datefmt: str = "%Y-%m-%d %H:%M:%S",
) -> Logger

Uses stdout for logging and installs it as current logger.

Source code in pygx/instrument/_logging.py
def use_stdout(
    level: int = logging.INFO,
    fmt: str = '{levelname:8} | {asctime} | {message}',
    datefmt: str = '%Y-%m-%d %H:%M:%S',
) -> logging.Logger:
    """Uses stdout for logging and installs it as current logger."""
    return use_stream(sys.stdout, level, 'stdout', fmt, datefmt)

redirect_stream

redirect_stream(
    stream: Any,
    level: int = INFO,
    name: str = "custom",
    fmt: str = "{levelname:8} | {asctime} | {message}",
    datefmt: str = "%Y-%m-%d %H:%M:%S",
) -> Iterator[Logger]

Context manager to log to the given stream within a scope.

Installs a stream-backed logger as the current logger for the duration of the scope, restoring the previous logger on exit.

Source code in pygx/instrument/_logging.py
@contextlib.contextmanager
def redirect_stream(
    stream: Any,
    level: int = logging.INFO,
    name: str = 'custom',
    fmt: str = '{levelname:8} | {asctime} | {message}',
    datefmt: str = '%Y-%m-%d %H:%M:%S',
) -> Iterator[logging.Logger]:
    """Context manager to log to the given stream within a scope.

    Installs a stream-backed logger as the current logger for the duration
    of the scope, restoring the previous logger on exit.
    """
    previous_logger = get_logger()
    try:
        logger = use_stream(stream, level, name, fmt, datefmt)
        yield logger
    finally:
        set_logger(previous_logger)

options: show_root_heading: false show_root_toc_entry: false members_order: source heading_level: 2