os_helper.logging_utils module

os_helper.logging_utils

ANSI-coloured root-logger setup and verbosity controls for the AI Helpers suite. Replaces bare print(...) calls across every helper with osh.info / osh.warning / osh.error (see the suite-wide style mandate in each helper’s CONTRIBUTING.md).

Usage example

>>> import os_helper as osh
>>> osh.verbosity(2)        # show DEBUG + INFO + WARNING + ERROR
>>> osh.info("hello %s", "world")
>>> osh.warning("disk %d%% full", 92)

Author

Warith HARCHAOUI — https://linkedin.com/in/warith-harchaoui

os_helper.logging_utils.check(condition, msg='Assertion failed')[source]

Assert a condition, logging an error and raising if it fails.

Parameters:
  • condition (bool) – The predicate that must hold.

  • msg (str, optional) – Message logged and attached to the raised error on failure.

Raises:

AssertionError – If condition is falsy.

Return type:

None

os_helper.logging_utils.critical(msg, *args, **kwargs)[source]

Log a message at CRITICAL level via the dedicated os_helper logger.

Parameters:
  • msg (str) – The (possibly %-style) message template.

  • *args (Any) – Positional interpolation arguments forwarded to logging.critical.

  • **kwargs (Any) – Keyword options forwarded to logging.critical.

Return type:

None

os_helper.logging_utils.debug(msg, *args, **kwargs)[source]

Log a message at DEBUG level via the dedicated os_helper logger.

Parameters:
  • msg (str) – The (possibly %-style) message template.

  • *args (Any) – Positional interpolation arguments forwarded to logging.debug.

  • **kwargs (Any) – Keyword options (e.g. exc_info) forwarded to logging.debug.

Return type:

None

os_helper.logging_utils.error(msg, *args, **kwargs)[source]

Log a message at ERROR level via the dedicated os_helper logger.

Note: this is a non-raising logger call. It will not terminate the program. Use check() (assertion-style) or raise an exception explicitly if you need failure semantics.

Parameters:
  • msg (str) – The (possibly %-style) message template.

  • *args (Any) – Positional interpolation arguments forwarded to logging.error.

  • **kwargs (Any) – Keyword options forwarded to logging.error.

Return type:

None

os_helper.logging_utils.info(msg, *args, **kwargs)[source]

Log a message at INFO level via the dedicated os_helper logger.

Parameters:
  • msg (str) – The (possibly %-style) message template.

  • *args (Any) – Positional interpolation arguments forwarded to logging.info.

  • **kwargs (Any) – Keyword options forwarded to logging.info.

Return type:

None

os_helper.logging_utils.init_logging(*, level=20, stdout=True, log_format='%(asctime)s | %(levelname)s | %(name)s | %(message)s', date_format='%Y-%m-%d %H:%M:%S', filename=None, capture_warnings=True, reset=True, use_colors=True, propagate=False, name=None, live_stream=False)[source]

Initialize application-wide logging.

This function configures the root logger with a console handler and, optionally, a file handler. It is designed for applications, scripts, notebooks, and machine learning experiments where deterministic logging setup is useful.

Parameters:
  • level (int, optional) – Logging level applied to the root logger and its handlers. Typical values are logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, and logging.CRITICAL.

  • stdout (bool, optional) – If True, console logs are sent to sys.stdout. Otherwise, they are sent to sys.stderr.

  • log_format (str, optional) – Format string used for log records.

  • date_format (str, optional) – Format string used for timestamps in log records.

  • filename (str | pathlib.Path | None, optional) – Optional path to a log file. If provided, logs are also written to this file using UTF-8 encoding.

  • capture_warnings (bool, optional) – If True, warnings emitted through the warnings module are redirected to the logging system.

  • reset (bool, optional) – If True, existing handlers attached to the root logger are removed before adding new ones. This is often desirable in notebooks and interactive sessions to avoid duplicated messages.

  • use_colors (bool, optional) – If True, colorize console log levels when ANSI colors are supported. File logs are never colorized.

  • propagate (bool, optional) – Value assigned to the target logger’s propagation flag. False avoids duplicates for the root logger; a named logger (see name) often wants True so its records still reach a host’s / pytest’s root handlers (e.g. caplog).

  • name (str | None, optional) – Configure this named logger instead of the root. When set, the reset step only removes handlers this function installed (so a host’s / pytest’s handlers on that logger survive), and repeated calls are idempotent — a second call does not stack a duplicate console handler. This is the CLI-friendly mode: configure "mytool" once, keep propagate=True, and every logging.getLogger("mytool.*") inherits the handler + level.

  • live_stream (bool, optional) – If True, the console handler re-resolves sys.stdout/sys.stderr on every emit instead of binding the stream once. This keeps output flowing to wherever the stream currently points — surviving pytest’s capsys (which swaps the streams per test) and any post-config redirection. The default keeps the classic bound-stream handler.

Returns:

The configured logger (the root logger, or the one named by name).

Return type:

logging.Logger

Notes

This function is intended for top-level applications, notebooks, and experimentation code. Reusable libraries should generally avoid configuring global logging and should instead use:

logger = logging.getLogger(__name__)

Examples

>>> logger = init_logging(level=logging.DEBUG, filename="experiment.log")
>>> logger.info("Logging is configured.")
>>> logger = init_logging(use_colors=True, reset=True)
>>> logger.warning("This is a warning.")
os_helper.logging_utils.verbosity(level=None)[source]

Get or set the current root logger verbosity.

Called with no argument, returns the current verbosity as an integer. Called with an integer, updates the root logger (and its existing handlers) accordingly and returns the new effective verbosity.

Mapping (higher = more verbose):

  • >= 2 → DEBUG

  • 1 → INFO

  • 0 → WARNING

  • -1 → ERROR

  • <= -2 → CRITICAL

Values outside [-2, 2] are clamped (e.g. verbosity(3) is treated as DEBUG, matching the convenience usage shown in the README).

Parameters:

level (int | None, optional) – New verbosity level to apply, or None to just read the current value.

Returns:

Current (post-update, when setting) verbosity as an integer in the range [-2, 2].

Return type:

int

Examples

>>> verbosity(2)   # turn on DEBUG-level logging
2
>>> verbosity()    # read current level
2
os_helper.logging_utils.warning(msg, *args, **kwargs)[source]

Log a message at WARNING level via the dedicated os_helper logger.

Parameters:
  • msg (str) – The (possibly %-style) message template.

  • *args (Any) – Positional interpolation arguments forwarded to logging.warning.

  • **kwargs (Any) – Keyword options forwarded to logging.warning.

Return type:

None