Skip to content

API reference (auto-generated)

Exhaustive mkdocstrings reference generated from source docstrings.

🔍 Full package dump

ezplog

Ezpl - Modern Python logging framework.

Ezpl is a modern Python library for advanced log management, using Rich for console output and loguru for file logging, with a simple and typed API, suitable for professional and industrial applications.

Main Features: - Singleton pattern for global logging instance - Rich-based console output with colors and formatting - Loguru-based file logging with rotation support - Contextual indentation management - Pattern-based logging (SUCCESS, ERROR, WARN, TIP, etc.) - JSON display support - Robust error handling

Two usage modes:

App mode — configure once at application level:

>>> from ezplog import Ezpl
>>> ezpl = Ezpl(log_file="app.log", hook_logger=True, lock_config=True)
>>> ezpl.info("Application started")           # direct facade
>>> ezpl.get_printer().success("Ready")        # advanced usage

Lib mode — passive proxies for library authors:

>>> from ezplog.lib_mode import get_logger, get_printer
>>> log = get_logger(__name__)
>>> printer = get_printer()
>>> log.info("Library initialized")            # silent without host config
>>> printer.success("Library initialized")     # silent without host config

Printer module-attribute

Printer = EzPrinter

Type alias for EzPrinter (console printer handler). Use this type when you want to annotate a variable that represents a printer.

Example

from ezplog import Ezpl, Printer ezpl = Ezpl() printer: Printer = ezpl.get_printer() printer.info("Hello!") printer.success("Done!") printer.print_json({"key": "value"})

Logger module-attribute

Logger = EzLogger

Type alias for EzLogger (file logger handler). Use this type when you want to annotate a variable that represents a logger.

Example

from ezplog import Ezpl, Logger ezpl = Ezpl() logger: Logger = ezpl.get_logger() logger.info("Logged to file")

InterceptHandler

Bases: Handler

Redirect stdlib logging records to loguru.

This handler bridges the stdlib logging system and loguru, allowing libraries that use logging.getLogger(name) to have their output captured by the loguru pipeline configured by ezpl.

The caller frame is resolved by walking up the call stack past logging internals, so the log records appear with the correct source location in loguru output.

Example

import logging from ezpl import Ezpl, InterceptHandler

Option 1 — automatic via Ezpl

ezpl = Ezpl(log_file="app.log", hook_logger=True)

Option 2 — manual installation

logging.basicConfig(handlers=[InterceptHandler()], level=0, force=True)

emit

emit(record: LogRecord) -> None

Forward a stdlib LogRecord to loguru.

Parameters:

Name Type Description Default
record LogRecord

The log record emitted by a stdlib logger.

required

ConfigurationManager

ConfigurationManager(config_file: Path | None = None)

Centralized configuration manager for Ezpl.

This class handles all configuration operations including loading, saving, and merging configuration from multiple sources.

Initialize the configuration manager.

Parameters:

Name Type Description Default
config_file Path | None

Optional path to configuration file. Defaults to ~/.ezpl/config.json

None

config_file property

config_file: Path

Return the path to the configuration file.

get

get(key: str, default: Any = None) -> Any

Get a configuration value.

Parameters:

Name Type Description Default
key str

Configuration key

required
default Any

Default value if key not found

None

Returns:

Type Description
Any

Configuration value or default

has_key

has_key(key: str) -> bool

Check if a configuration key is explicitly set (not just a default).

A key is considered explicit when it comes from a config file, an environment variable, or a direct call to configure()/set()/update(). Keys that are present only because of default values return False.

Parameters:

Name Type Description Default
key str

Configuration key to check

required

Returns:

Type Description
bool

True if the key was explicitly set, False if it is only a default.

get_log_level

get_log_level() -> str

Get the current log level.

get_log_file

get_log_file() -> Path

Get the current log file path.

get_printer_level

get_printer_level() -> str

Get the current printer level.

get_file_logger_level

get_file_logger_level() -> str

Get the current file logger level.

get_indent_step

get_indent_step() -> int

Get the current indent step.

get_indent_symbol

get_indent_symbol() -> str

Get the current indent symbol.

get_base_indent_symbol

get_base_indent_symbol() -> str

Get the current base indent symbol.

get_log_format

get_log_format() -> str

Get the current log format.

get_log_rotation

get_log_rotation() -> str | None

Get the current log rotation setting.

get_log_retention

get_log_retention() -> str | None

Get the current log retention setting.

get_log_compression

get_log_compression() -> str | None

Get the current log compression setting.

get_all

get_all() -> dict[str, Any]

Get all configuration values.

Returns:

Type Description
dict[str, Any]

Dictionary containing all configuration values

set

set(key: str, value: Any) -> None

Set a configuration value.

Parameters:

Name Type Description Default
key str

Configuration key

required
value Any

Configuration value

required

update

update(config_dict: dict[str, Any]) -> None

Update configuration with new values.

Parameters:

Name Type Description Default
config_dict dict[str, Any]

Dictionary of configuration values to update

required

save

save() -> None

Save current configuration to file.

Raises:

Type Description
FileOperationError

If unable to write to configuration file

reset_to_defaults

reset_to_defaults() -> None

Reset configuration to default values.

reload

reload() -> None

Reload configuration from file and environment variables.

This method reloads the configuration, useful when environment variables or the config file have changed after initialization.

export_to_script

export_to_script(output_file: str | Path, platform: str | None = None) -> None

Export configuration as environment variables script.

Parameters:

Name Type Description Default
output_file str | Path

Path to output script file

required
platform str | None

Target platform ('windows', 'unix', or None for auto-detect)

None

Raises:

Type Description
FileOperationError

If unable to write to output file

ConfigurationError

ConfigurationError(message: str, config_key: str | None = None)

Bases: EzplError

Exception raised for configuration-related errors.

This exception is raised when configuration loading, validation, or processing encounters issues. The optional config_key attribute helps identify which configuration parameter caused the problem.

Initialize the configuration error.

Parameters:

Name Type Description Default
message str

Human-readable error message

required
config_key str | None

Optional configuration key that caused the error

None

EzplError

EzplError(message: str, error_code: str | None = None)

Bases: Exception

Base exception class for all Ezpl-related errors.

All custom exceptions in the Ezpl framework inherit from this base class, enabling centralized exception handling and consistent error reporting. Each exception includes a message and optional error code for categorization.

Initialize the Ezpl error.

Parameters:

Name Type Description Default
message str

Human-readable error message

required
error_code str | None

Optional error code for categorization and debugging

None
Note

Error codes follow the pattern: COMPONENT_ERROR or OPERATION_ERROR (e.g., "CONFIG_ERROR", "FILE_ERROR") for consistent error tracking.

FileOperationError

FileOperationError(message: str, file_path: str | None = None, operation: str | None = None)

Bases: EzplError

Exception raised for file operation errors.

This exception covers issues with file operations (reading, writing, creating files). The optional file_path and operation attributes help identify which file and operation (read, write, create) failed.

Initialize the file operation error.

Parameters:

Name Type Description Default
message str

Human-readable error message

required
file_path str | None

Optional file path that caused the error

None
operation str | None

Optional operation that failed (e.g., "read", "write", "create")

None

HandlerError

HandlerError(message: str, handler_name: str | None = None)

Bases: EzplError

Exception raised for handler-related errors.

This exception covers issues with logging handlers (initialization, configuration, operation failures). The optional handler_name attribute identifies which handler (EzPrinter, EzLogger) caused the problem.

Initialize the handler error.

Parameters:

Name Type Description Default
message str

Human-readable error message

required
handler_name str | None

Optional handler name that caused the error

None

InitializationError

InitializationError(message: str, component: str | None = None)

Bases: EzplError

Exception raised for initialization errors.

This exception is raised when Ezpl components fail to initialize properly. The optional component attribute identifies which component (printer, logger, config) encountered the initialization issue.

Initialize the initialization error.

Parameters:

Name Type Description Default
message str

Human-readable error message

required
component str | None

Optional component that failed to initialize

None

LoggingError

LoggingError(message: str, handler_type: str | None = None)

Bases: EzplError

Exception raised for logging-related errors.

This exception covers issues with logging operations such as file writing, format processing, or handler initialization. The optional handler_type attribute identifies which handler (console, file) caused the error.

Initialize the logging error.

Parameters:

Name Type Description Default
message str

Human-readable error message

required
handler_type str | None

Optional handler type that caused the error (e.g., "file", "console")

None

ValidationError

ValidationError(message: str, field_name: str | None = None, value: str | None = None)

Bases: EzplError

Exception raised for validation errors.

This exception is raised when input validation fails (e.g., invalid log levels, malformed configuration values). The optional field_name and value attributes help identify what was being validated when the error occurred.

Initialize the validation error.

Parameters:

Name Type Description Default
message str

Human-readable error message

required
field_name str | None

Optional field name that failed validation

None
value str | None

Optional value that failed validation

None

Ezpl

Main logging singleton for the Ezpl framework.

Ezpl provides a unified, thread-safe interface for console and file logging with advanced features including indentation management, pattern-based logging, and dynamic progress bars. It implements the Singleton pattern to ensure only one instance exists throughout the application lifecycle.

Attributes:

Name Type Description
_instance Ezpl | None

The singleton instance of Ezpl

_lock RLock

Thread lock for synchronized access

_config_locked bool

Whether configuration can be modified

_log_file Path

Path to the log file

_printer EzPrinter

Console output handler

_logger EzLogger

File logging handler

_config_manager ConfigurationManager

Configuration manager instance

Note

Once initialized, Ezpl cannot be re-configured unless reset. Access it via the singleton pattern or module-level functions.

Example

log = Ezpl() log.printer.log("INFO", "Application started") log.logger.log("INFO", "Starting logging to file")

printer_level property

printer_level: str

Return the current printer logging level.

logger_level property

logger_level: str

Return the current file logger logging level.

is_initialized classmethod

is_initialized() -> bool

Return True if the Ezpl singleton has already been created.

Useful for libraries that want to know whether they are the first to initialize Ezpl or if they should avoid re-configuring it.

get_printer

get_printer() -> EzPrinter

Returns the EzPrinter instance.

Returns:

* EzPrinter: The console printer instance providing info(), debug(), success(), etc.
    Implements PrinterProtocol for type safety.

get_logger

get_logger() -> EzLogger

Returns the EzLogger instance.

Returns:

* EzLogger: The file logger instance for file logging.
    Use logger.info(), logger.debug(), etc. directly.
    For advanced loguru features, use logger.get_loguru()
    Implements LoggerProtocol for type safety.

set_level

set_level(level: str) -> None

Set the log level for both the printer and the logger simultaneously.

Args:

* `level` (str): The desired log level (e.g., "INFO", "WARNING").

Returns:

* `None`.

set_printer_level

set_printer_level(level: str) -> None

Set the log level for the printer only.

Args:

* `level` (str): The desired log level for the printer.

Returns:

* `None`.

set_logger_level

set_logger_level(level: str) -> None

Set the log level for the file logger only.

Args:

* `level` (str): The desired log level for the file logger.

Returns:

* `None`.

debug

debug(message: Any) -> None

Log a debug message to the console printer.

info

info(message: Any) -> None

Log an info message to the console printer.

success

success(message: Any) -> None

Log a success message to the console printer.

warning

warning(message: Any) -> None

Log a warning message to the console printer.

error

error(message: Any) -> None

Log an error message to the console printer.

critical

critical(message: Any) -> None

Log a critical message to the console printer.

add_separator

add_separator() -> None

Adds a separator to the log file.

Returns:

* `None`.

manage_indent

manage_indent() -> Generator[None, None, None]

Context manager to manage indentation level.

Returns:

* `None`.

reset classmethod

reset() -> None

Reset the singleton instance (useful for testing).

Warning: This will destroy the current instance and all its state.

set_compatibility_hooks

set_compatibility_hooks(*, hook_logger: bool = True, hook_printer: bool = True, logger_names: list[str] | None = None) -> None

Configure compatibility hooks between Ezpl and classic logging/lib_mode.

Parameters:

Name Type Description Default
hook_logger bool

If True, bridge stdlib logging records to Ezpl. If False, remove previously installed stdlib bridges.

True
hook_printer bool

If True, ezpl.lib_mode.get_printer() delegates to Ezpl's real printer once initialized. If False, it stays silent.

True
logger_names list[str] | None

Optional stdlib logger names to hook explicitly. When omitted, root logger is targeted.

None
Notes
  • This method is safe to call multiple times (idempotent behavior).
  • Hooking named loggers is useful for libraries with propagate=False.

lock_config classmethod

lock_config() -> str

Lock Ezpl configuration so that future configure() and set_level() calls are blocked until unlock_config(token) is called.

Intended usage
  1. Root application configures Ezpl once
  2. Calls token = Ezpl.lock_config()
  3. Stores the token; libraries cannot reconfigure Ezpl without it

Returns:

Name Type Description
str str

A token required to unlock the configuration later.

unlock_config classmethod

unlock_config(token: str) -> bool

Unlock Ezpl configuration.

Parameters:

Name Type Description Default
token str

The token returned by lock_config(). Must match exactly.

required

Returns:

Type Description
bool

True if unlocked successfully, False if the token is wrong.

is_locked classmethod

is_locked() -> bool

Return True if the configuration is currently locked.

is_lib_printer_hook_enabled classmethod

is_lib_printer_hook_enabled() -> bool

Return True when lib_mode printer proxy is allowed to delegate.

set_log_file

set_log_file(log_file: Path | str) -> None

Change the log file (requires reinitialization of the logger).

Parameters:

Name Type Description Default
log_file Path | str

New path to the log file

required

Note: This will reinitialize the file logger but keep the singleton instance.

get_log_file

get_log_file() -> Path

Get the current log file path.

Returns:

Type Description
Path

Path to the current log file

get_config

get_config() -> ConfigurationManager

Get the current configuration manager.

Returns:

Type Description
ConfigurationManager

ConfigurationManager instance for accessing and modifying configuration

set_printer_class

set_printer_class(printer_class: type[EzPrinter] | EzPrinter, **init_kwargs: Any) -> None

Replace the current printer with a custom printer class or instance.

Allows users to override the default printer with a custom class that inherits from EzPrinter. The method preserves current configuration values (level, indentation settings) unless explicitly overridden in init_kwargs.

Parameters:

Name Type Description Default
printer_class type[EzPrinter] | EzPrinter

Custom printer class inheriting from EzPrinter, or an already instantiated EzPrinter instance

required
**init_kwargs Any

Optional initialization parameters for the printer class. If not provided, current configuration values are used.

{}

Raises:

Type Description
TypeError

If printer_class is not a valid class or instance

ValidationError

If initialization parameters are invalid

Example

from ezpl import Ezpl, EzPrinter

class CustomPrinter(EzPrinter): ... def info(self, message): ... super().info(f"[CUSTOM] {message}")

ezpl = Ezpl() ezpl.set_printer_class(CustomPrinter, level="DEBUG") ezpl.get_printer().info("Test") [CUSTOM] Test

set_logger_class

set_logger_class(logger_class: type[EzLogger] | EzLogger, **init_kwargs: Any) -> None

Replace the current logger with a custom logger class or instance.

Allows users to override the default logger with a custom class that inherits from EzLogger. The method preserves current configuration values (level, rotation, retention, compression) unless explicitly overridden in init_kwargs.

Parameters:

Name Type Description Default
logger_class type[EzLogger] | EzLogger

Custom logger class inheriting from EzLogger, or an already instantiated EzLogger instance

required
**init_kwargs Any

Optional initialization parameters for the logger class. If not provided, current configuration values are used.

{}

Raises:

Type Description
TypeError

If logger_class is not a valid class or instance

ValidationError

If initialization parameters are invalid

FileOperationError

If file operations fail during logger creation (may be raised by the logger class constructor)

Example

from ezpl import Ezpl, EzLogger

class CustomLogger(EzLogger): ... def info(self, message): ... super().info(f"[CUSTOM LOG] {message}")

ezpl = Ezpl() ezpl.set_logger_class(CustomLogger, log_file="custom.log") ezpl.get_logger().info("Test")

reload_config

reload_config() -> None

Reload configuration from file and environment variables.

This method reloads the configuration and reapplies it to handlers. Useful when environment variables or the config file have changed after the singleton was initialized.

Note: This will reinitialize handlers with the new configuration.

configure

configure(config_dict: dict[str, Any] | None = None, *, persist: bool = False, **kwargs: Any) -> bool

Configure Ezpl dynamically.

Parameters:

Name Type Description Default
config_dict dict[str, Any] | None

Dictionary of configuration values to update

None
persist bool

If True, write changes to ~/.ezpl/config.json so they survive future runs. Defaults to False (in-memory only).

False
**kwargs Any

Configuration options (alternative to config_dict): - log_file or log-file: Path to log file - printer_level or printer-level: Printer log level - file_logger_level or file-logger-level: File logger level - level or log-level: Set both printer and logger level - log_rotation or log-rotation: Rotation setting (e.g., "10 MB", "1 day") - log_retention or log-retention: Retention period (e.g., "7 days") - log_compression or log-compression: Compression format (e.g., "zip", "gz") - indent_step or indent-step: Indentation step size - indent_symbol or indent-symbol: Symbol for indentation - base_indent_symbol or base-indent-symbol: Base indentation symbol

{}

Returns:

Type Description
bool

True if configuration was applied, False if it was blocked by lock.

EzLogger

EzLogger(log_file: Path | str, level: str = 'INFO', rotation: str | None = None, retention: str | None = None, compression: str | None = None)

Bases: LoggingHandler

File logger handler with advanced formatting and session management.

This handler provides file-based logging with: - Structured log format - Session separators - HTML tag sanitization - Automatic file creation

Initialize the file logger handler.

Parameters:

Name Type Description Default
log_file Path | str

Path to the log file

required
level str

The desired logging level

'INFO'
rotation str | None

Rotation size (e.g., "10 MB") or time (e.g., "1 day")

None
retention str | None

Retention period (e.g., "7 days")

None
compression str | None

Compression format (e.g., "zip", "gz")

None

Raises:

Type Description
ValidationError

If the provided level is invalid

FileOperationError

If file operations fail

level property

level: str

Return the current logging level.

level_manually_set property

level_manually_set: bool

Return whether level was set manually at runtime.

rotation property

rotation: str | None

Return current rotation setting.

retention property

retention: str | None

Return current retention setting.

compression property

compression: str | None

Return current compression setting.

mark_level_as_configured

mark_level_as_configured() -> None

Mark the current level as coming from configuration (not manual set).

set_level

set_level(level: str) -> None

Set the logging level.

Parameters:

Name Type Description Default
level str

The desired logging level

required

Raises:

Type Description
ValidationError

If the provided level is invalid

LoggingError

If level update fails

log

log(level: str, message: Any) -> None

Log a message with the specified level.

Parameters:

Name Type Description Default
level str

The log level

required
message Any

The message to log (any type, will be converted to string)

required

Raises:

Type Description
ValidationError

If the level is invalid

LoggingError

If logging fails

trace

trace(message: Any, *args, **kwargs) -> None

Log a trace message.

debug

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

Log a debug message.

info

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

Log an info message.

success

success(message: Any, *args, **kwargs) -> None

Log a success message.

warning

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

Log a warning message.

error

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

Log an error message.

critical

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

Log a critical message.

exception

exception(message: Any, *args, **kwargs) -> None

Log an exception with traceback.

bind

bind(**kwargs: Any) -> Any

Bind context variables to the logger.

opt

opt(**kwargs: Any) -> Any

Configure logger options.

patch

patch(patcher: Any) -> Any

Patch log records.

get_loguru

get_loguru() -> Logger

Get the underlying Loguru logger instance for advanced usage.

Returns:

* loguru.Logger: The loguru logger instance

Raises:

* LoggingError: If the logger is not initialized

get_log_file

get_log_file() -> Path

Get the current log file path.

Returns:

Type Description
Path

Path to the log file

get_file_size

get_file_size() -> int

Get the current log file size in bytes.

Returns:

Type Description
int

File size in bytes, or 0 if file doesn't exist or error occurs

close

close() -> None

Close the logger handler and release file handles.

This method removes the loguru handler to release file handles, which is especially important on Windows where files can remain locked.

add_separator

add_separator() -> None

Add a separator line to the log file for session distinction.

Raises:

Type Description
FileOperationError

If writing to the log file fails

EzPrinter

EzPrinter(level: str = 'INFO', indent_step: int = 3, indent_symbol: str = '>', base_indent_symbol: str = '~')

Bases: LoggingHandler, IndentationManager

Console printer handler with advanced formatting and indentation support using Rich.

This handler provides console-based logging with: - Color-coded log levels using Rich - Indentation management - Robust character handling (Rich handles special characters automatically) - Context manager support - Pattern-based logging (SUCCESS, ERROR, WARN, TIP, etc.) - Access to RichWizard for advanced display features

Initialize the console printer handler.

Parameters:

Name Type Description Default
level str

The desired logging level

'INFO'
indent_step int

Number of spaces for each indentation level

3
indent_symbol str

Symbol for indentation levels

'>'
base_indent_symbol str

Symbol for the base indentation

'~'

Raises:

Type Description
ValidationError

If the provided level is invalid

level property

level: str

Return the current logging level.

level_manually_set property

level_manually_set: bool

Return whether level was set manually at runtime.

indent_step property

indent_step: int

Return the configured indentation step.

indent_symbol property

indent_symbol: str

Return the configured indentation symbol.

base_indent_symbol property

base_indent_symbol: str

Return the configured base indentation symbol.

wizard property

wizard: RichWizard

Get the Rich Wizard instance for advanced display features.

Returns:

Type Description
RichWizard

RichWizard instance for panels, tables, JSON, etc.

Example

printer.wizard.success_panel("Success", "Operation completed") printer.wizard.status_table("Status", data) printer.wizard.dependency_table({"tool": "1.0.0"})

mark_level_as_configured

mark_level_as_configured() -> None

Mark the current level as coming from configuration (not manual set).

set_level

set_level(level: str) -> None

Set the logging level.

Parameters:

Name Type Description Default
level str

The desired logging level

required

Raises:

Type Description
ValidationError

If the provided level is invalid

log

log(level: str, message: Any) -> None

Log a message with the specified level.

Parameters:

Name Type Description Default
level str

The log level

required
message Any

The message to log (any type, will be safely converted to string)

required

Raises:

Type Description
ValidationError

If the level is invalid

info

info(message: Any) -> None

Log an informational message with pattern format.

debug

debug(message: Any) -> None

Log a debug message with pattern format.

success

success(message: Any) -> None

Log a success message with pattern format.

warning

warning(message: Any) -> None

Log a warning message with pattern format.

error

error(message: Any) -> None

Log an error message with pattern format.

critical

critical(message: Any) -> None

Log a critical message with pattern format.

tip

tip(message: Any) -> None

Display a tip message with pattern format.

system

system(message: Any) -> None

Display a system message with pattern format.

install

install(message: Any) -> None

Display an installation message with pattern format.

detect

detect(message: Any) -> None

Display a detection message with pattern format.

config

config(message: Any) -> None

Display a configuration message with pattern format.

deps

deps(message: Any) -> None

Display a dependencies message with pattern format.

print_pattern

print_pattern(pattern: str | Pattern, message: Any, level: str = 'INFO') -> None

Display a message with pattern format: • PATTERN :: message

Parameters:

Name Type Description Default
pattern str | Pattern

Pattern name (string) or Pattern enum

required
message Any

Message to display

required
level str

Log level for filtering (default: INFO)

'INFO'

get_indent

get_indent() -> str

Get the current indentation string.

Returns:

Type Description
str

The current indentation string

add_indent

add_indent() -> None

Increase the indentation level by one (with maximum limit).

del_indent

del_indent() -> None

Decrease the indentation level by one, ensuring it doesn't go below zero.

reset_indent

reset_indent() -> None

Reset the indentation level to zero.

manage_indent

manage_indent() -> Generator[None, None, None]

Context manager for temporary indentation.

Yields:

Type Description
None

None

print_table

print_table(data: list[dict[str, Any]], title: str | None = None) -> None

Display a table using Rich (delegates to RichWizard).

Parameters:

Name Type Description Default
data list[dict[str, Any]]

List of dictionaries representing table rows

required
title str | None

Optional table title

None

print_panel

print_panel(content: str, title: str | None = None, style: str = 'blue') -> None

Display a panel using Rich (delegates to RichWizard).

Parameters:

Name Type Description Default
content str

Panel content

required
title str | None

Optional panel title

None
style str

Panel style (Rich style string, used as border_style)

'blue'

print_progress

print_progress(*args, **kwargs) -> None

Display a progress bar using Rich.

Note: This is a placeholder. For full progress functionality, users should use Rich's Progress context manager directly.

print_json

print_json(data: str | dict | list, title: str | None = None, indent: int | None = None, highlight: bool = True) -> None

Display JSON data in a formatted and syntax-highlighted way using Rich (delegates to RichWizard).

Parameters:

Name Type Description Default
data str | dict | list

JSON data to display (dict, list, or JSON string)

required
title str | None

Optional title for the JSON display

None
indent int | None

Number of spaces for indentation (default: 2)

None
highlight bool

Whether to enable syntax highlighting (default: True)

True

Examples:

>>> printer.print_json({"name": "Alice", "age": 30})
>>> printer.print_json('{"key": "value"}', title="Config")
>>> printer.print_json([1, 2, 3], indent=4)

RichWizard

RichWizard(console: Console)

Bases: PanelMixin, TableMixin, JsonMixin, ProgressMixin, DynamicProgressMixin

Rich Wizard for advanced console display capabilities.

This class provides specialized methods for creating and displaying Rich-based panels, tables, JSON, and other formatted outputs, including advanced progress bars.

The class combines multiple mixins to provide a unified API: - PanelMixin: Panel display methods - TableMixin: Table display methods - JsonMixin: JSON display methods - ProgressMixin: Progress bar methods - DynamicProgressMixin: Dynamic layered progress bar methods

Initialize the Rich Wizard.

Parameters:

Name Type Description Default
console Console

Rich Console instance to use for output

required

DynamicLayeredProgress

DynamicLayeredProgress(console: Console, progress_prefix: str, stages: list[StageConfig], show_time: bool = True)

Manages a dynamic layered progress bar with disappearing layers.

This class provides a progress bar system where layers can appear, progress, and disappear based on the current state of operations.

Initialize the dynamic layered progress bar.

Parameters:

Name Type Description Default
console Console

Rich Console instance

required
progress_prefix str

Prefix string for progress bars

required
stages list[StageConfig]

List of stage configurations

required
show_time bool

Whether to show elapsed and remaining time

True

update_layer

update_layer(layer_name: str, progress: int, details: str = '') -> None

Update a specific layer's progress.

Parameters:

Name Type Description Default
layer_name str

Name of the layer to update

required
progress int

Progress value (0-100 or step index)

required
details str

Additional details to display

''

complete_layer

complete_layer(layer_name: str) -> None

Mark a layer as completed and animate its success.

Parameters:

Name Type Description Default
layer_name str

Name of the layer to complete

required

handle_error

handle_error(layer_name: str, error: str) -> None

Handle errors in a specific layer.

Parameters:

Name Type Description Default
layer_name str

Name of the layer with error

required
error str

Error message to display

required

emergency_stop

emergency_stop(error_message: str = 'Critical error occurred') -> None

Emergency stop all layers with animated failure effects.

Parameters:

Name Type Description Default
error_message str

The error message to display

'Critical error occurred'

is_emergency_stopped

is_emergency_stopped() -> bool

Check if the progress bar was emergency stopped.

Returns:

Type Description
bool

True if emergency stopped, False otherwise

get_emergency_message

get_emergency_message() -> str | None

Get the emergency stop message.

Returns:

Type Description
str | None

The emergency message if stopped, None otherwise

start

start() -> None

Start the progress bar and create initial layers.

stop

stop(success: bool = True, show_success_animation: bool = True) -> None

Stop the progress bar with appropriate animations.

Parameters:

Name Type Description Default
success bool

Whether this stop represents a successful completion

True
show_success_animation bool

Whether to show success animations

True

StageConfig

Bases: _StageConfigRequired

Configuration for a DynamicLayeredProgress stage.

Required fields

name: Layer name/identifier. type: Layer type ("progress", "steps", "spinner", "download", "main").

Optional fields

description: Display description for the layer. style: Rich style string. total: Total items (for "progress" or "download" type). steps: List of step names (for "steps" or "main" type). total_size: Total size in bytes (for "download" type). filename: Filename (for "download" type).

LoggerProtocol

Bases: Protocol

Protocol defining the interface for logger implementations.

All logger implementations must conform to this protocol to ensure consistent API and type safety.

Required Methods: - Logging methods: info(), debug(), success(), warning(), error(), critical(), trace(), bind() - Utility methods: set_level(), log(), add_separator() - Getter methods: get_logger(), get_log_file()

Note: This protocol is designed to be compatible with loguru.Logger while allowing custom implementations.

level property

level: str

Get the current logging level.

trace

trace(message: Any, *args, **kwargs) -> None

Log a trace message.

debug

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

Log a debug message.

info

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

Log an info message.

success

success(message: Any, *args, **kwargs) -> None

Log a success message.

warning

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

Log a warning message.

error

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

Log an error message.

critical

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

Log a critical message.

exception

exception(message: Any, *args, **kwargs) -> None

Log an exception with traceback.

bind

bind(**kwargs: Any) -> Any

Bind context variables to the logger.

opt

opt(**kwargs: Any) -> Any

Configure logger options.

patch

patch(patcher: Any) -> Any

Patch log records.

set_level

set_level(level: str) -> None

Set the logging level.

log

log(level: str, message: Any) -> None

Log a message with specified level.

add_separator

add_separator() -> None

Add a session separator to the log file.

get_log_file

get_log_file() -> Path

Get the current log file path.

close

close() -> None

Close the logger and release resources.

LogLevel

LogLevel(label: str, no: int, fg: str, bg: str)

Bases: Enum

LogLevel is an enumeration representing different logging levels with associated names, numeric levels, and colorimetric configurations.

Attributes: * label: Human-readable name of the log level * no: Numeric level for comparison * fg: Foreground color code * bg: Background color code

Levels: * DEBUG: Debugging messages (lowest priority) * INFO: Informational messages * SUCCESS: Success messages * WARNING: Warning messages * ERROR: Error messages * CRITICAL: Critical messages (highest priority)

Initialize a LogLevel instance.

Parameters:

Name Type Description Default
label str

Human-readable name of the log level

required
no int

Numeric level for comparison

required
fg str

Foreground color code

required
bg str

Background color code

required

get_attribute classmethod

get_attribute(level: str, attribute: str) -> Any

Returns the specified attribute (label, no, fg, bg) for a given logging level.

Parameters:

Name Type Description Default
level str

The logging level name

required
attribute str

The attribute to retrieve ('label', 'no', 'fg', 'bg')

required

Returns:

Type Description
Any

The requested attribute value

Raises:

Type Description
ValueError

If the level or attribute is not found

get_label classmethod

get_label(level: str) -> str

Get the label for a given log level.

Parameters:

Name Type Description Default
level str

The logging level name

required

Returns:

Type Description
str

The label for the log level

get_no classmethod

get_no(level: str) -> int

Get the numeric level for a given log level.

Parameters:

Name Type Description Default
level str

The logging level name

required

Returns:

Type Description
int

The numeric level

get_fgcolor classmethod

get_fgcolor(level: str) -> str

Get the foreground color for a given log level.

Parameters:

Name Type Description Default
level str

The logging level name

required

Returns:

Type Description
str

The foreground color code

get_bgcolor classmethod

get_bgcolor(level: str) -> str

Get the background color for a given log level.

Parameters:

Name Type Description Default
level str

The logging level name

required

Returns:

Type Description
str

The background color code

is_valid_level classmethod

is_valid_level(level: str) -> bool

Check if a given level is valid.

Parameters:

Name Type Description Default
level str

The logging level name to check

required

Returns:

Type Description
bool

True if the level is valid, False otherwise

get_all_levels classmethod

get_all_levels() -> list[str]

Get all available log levels.

Returns:

Type Description
list[str]

List of all available log level names

get_rich_style

get_rich_style() -> str

Get the Rich style string for this log level.

Returns:

Type Description
str

Rich style string (e.g., "bold red", "cyan", etc.)

Pattern

Bases: Enum

Contextual patterns for console output.

Patterns provide semantic meaning beyond log levels, allowing for more expressive and contextual logging.

PrinterProtocol

Bases: Protocol

Protocol defining the interface for printer implementations.

All printer implementations must conform to this protocol to ensure consistent API and type safety.

Required Methods: - Logging methods: info(), debug(), success(), warning(), error(), critical() - Pattern methods: tip(), system(), install(), detect(), config(), deps() - Enhanced methods: print_pattern(), print_json() - Utility methods: set_level(), log() - Indentation methods: add_indent(), del_indent(), reset_indent(), manage_indent()

Required Properties: - wizard: Access to RichWizard instance for advanced features

level property

level: str

Get the current logging level.

wizard property

wizard: Any

Get RichWizard instance for advanced features.

info

info(message: Any) -> None

Log an info message.

debug

debug(message: Any) -> None

Log a debug message.

success

success(message: Any) -> None

Log a success message.

warning

warning(message: Any) -> None

Log a warning message.

error

error(message: Any) -> None

Log an error message.

critical

critical(message: Any) -> None

Log a critical message.

tip

tip(message: Any) -> None

Display a tip message.

system

system(message: Any) -> None

Display a system message.

install

install(message: Any) -> None

Display an installation message.

detect

detect(message: Any) -> None

Display a detection message.

config

config(message: Any) -> None

Display a configuration message.

deps

deps(message: Any) -> None

Display a dependencies message.

print_pattern

print_pattern(pattern: str | Pattern, message: Any, level: str = 'INFO') -> None

Display a message with pattern format.

print_json

print_json(data: str | dict | list, title: str | None = None, indent: int | None = None, highlight: bool = True) -> None

Display JSON data in formatted way.

set_level

set_level(level: str) -> None

Set the logging level.

log

log(level: str, message: Any) -> None

Log a message with specified level.

add_indent

add_indent() -> None

Increase indentation level.

del_indent

del_indent() -> None

Decrease indentation level.

reset_indent

reset_indent() -> None

Reset indentation to zero.

manage_indent

manage_indent() -> AbstractContextManager[None]

Context manager for temporary indentation.

get_logger

get_logger(name: str) -> Logger

Return a stdlib-compatible logger for use in library code.

The returned logger has a NullHandler attached so that no output is produced when the host application has not configured any handler. When the host application enables logger hooks in Ezpl, all records emitted by this logger are automatically forwarded to the Rich/loguru pipeline.

This follows the official Python recommendation for library logging: https://docs.python.org/3/howto/logging.html#configuring-logging-for-a-library

Parameters:

Name Type Description Default
name str

Logger name. Use name to follow the module-name convention, which allows the host application to filter by package prefix.

required

Returns:

Type Description
Logger

logging.Logger: A stdlib logger, passive by design.

Example

from ezpl.lib_mode import get_logger log = get_logger(name) log.info("Service initialized") # silent without host config log.warning("Unexpected state") # forwarded if intercepted

get_printer

get_printer() -> _LazyPrinter

Return the shared lazy printer proxy for use in library code.

The returned proxy silently discards all method calls when the host application has not initialized Ezpl. Once the app calls Ezpl(...), every subsequent call is transparently forwarded to the real EzPrinter.

The same instance is returned on every call (module-level singleton). The proxy is stateless — it holds no indentation or level state of its own, delegating everything to the real EzPrinter when available.

No configuration is triggered by calling this function — it is safe to call at module level in library code.

Returns:

Name Type Description
_LazyPrinter _LazyPrinter

A lazy proxy implementing the full EzPrinter interface.

Example

from ezpl.lib_mode import get_printer printer = get_printer() printer.success("Service ready") # silent without host config printer.info("Processing...") # delegated once app initializes Ezpl with printer.manage_indent(): ... printer.debug("detail")

get_pattern_color

get_pattern_color(pattern: Pattern) -> str

Get the Rich color style for a pattern.

Parameters:

Name Type Description Default
pattern Pattern

The pattern to get the color for

required

Returns:

Type Description
str

Rich color style string

get_pattern_color_by_name

get_pattern_color_by_name(pattern_name: str) -> str

Get the Rich color style for a pattern by name.

Parameters:

Name Type Description Default
pattern_name str

The pattern name (case-insensitive)

required

Returns:

Type Description
str

Rich color style string