Configuration

Configuration Management Module for prismalog

This module provides a centralized configuration system for the prismalog package, enabling flexible and hierarchical configuration from multiple sources. It handles loading, prioritizing, and accessing configuration settings throughout the application.

Key features: - Hierarchical configuration with clear priority order - Multi-source configuration (default values, files, environment variables, CLI) - Support for YAML configuration files - Automatic type conversion for numeric and boolean values - Command-line argument integration with argparse - Singleton pattern to ensure configuration consistency

The configuration system follows this priority order (highest to lowest): 1. Programmatic settings via direct API calls or kwargs to initialize() 2. Command-line arguments 3. Configuration files (YAML) 4. Environment variables (with support for CI/CD environments) 5. Default values

Environment Variables:

Standard environment variables use the LOG_ prefix:

  • LOG_DIR: Directory for log files

  • LOG_LEVEL: Default logging level (e.g., INFO, DEBUG)

  • LOG_ROTATION_SIZE: Size in MB for log rotation

  • LOG_BACKUP_COUNT: Number of backup log files

  • LOG_FORMAT: Log message format string

  • LOG_DATEFMT: Log message date format string

  • LOG_FILENAME: Base filename prefix for log files (default: ‘app’)

  • LOG_COLORED_CONSOLE: Whether to use colored console output (true/false)

  • LOG_DISABLE_ROTATION: Whether to disable log rotation (true/false)

  • LOG_EXIT_ON_CRITICAL: Whether to exit on critical logs (true/false)

  • LOG_TEST_MODE: Whether logger is in test mode (true/false)

For GitHub Actions, the same variables are supported with GITHUB_ prefix:

  • GITHUB_LOG_DIR, GITHUB_LOG_LEVEL, GITHUB_LOG_FILENAME, GITHUB_LOG_DATEFMT, etc.

Command-Line Arguments:

The following arguments can be parsed if use_cli_args=True during initialization:

  • --log-config / --log-conf: Path to logging configuration file (YAML)

  • --log-level / --logging-level: Default logging level (DEBUG, INFO, etc.)

  • --log-dir / --logging-dir: Directory for log files

  • --log-format / --logging-format: Format string for log messages

  • --log-datefmt / --logging-datefmt: Format string for log timestamps

  • --log-filename / --logging-filename: Prefix for log filenames

  • --no-color / --no-colors: Disable colored console output

  • --disable-rotation: Disable log file rotation

  • --exit-on-critical: Exit the program on critical errors

  • --rotation-size: Log file rotation size in MB

  • --backup-count: Number of backup log files to keep

Type Conversion:

String values from configuration files and environment variables are automatically converted to the appropriate types (boolean, integer) based on the default config’s type definition. Boolean values support multiple string representations: - True: “true”, “1”, “yes”, “y”, “t”, “on” - False: “false”, “0”, “no”, “n”, “f”, “off”, “none”

Usage examples:

# Basic initialization with defaults LoggingConfig.initialize()

# Initialization with configuration file and CLI args enabled LoggingConfig.initialize(config_file=”logging_config.yaml”, use_cli_args=True)

# Accessing configuration values log_dir = LoggingConfig.get(“log_dir”) filename_prefix = LoggingConfig.get_filename_prefix()

# Setting configuration values programmatically LoggingConfig.set(“colored_console”, False)

# Getting appropriate log level for a specific logger level = LoggingConfig.get_level(“requests.packages.urllib3”)

class prismalog.config.LoggingConfig[source]

Bases: object

Configuration manager for prismalog package.

Handles loading configuration from multiple sources with a priority order: 1. Programmatic settings 2. Command-line arguments 3. Configuration files (YAML) 4. Environment variables (including GitHub Actions secrets) 5. Default values

This class uses a singleton pattern to ensure consistent configuration throughout the application lifecycle. It supports configuration from multiple sources and provides automatic type conversion.

Return type:

LoggingConfig

DEFAULT_CONFIG

Default configuration values

Type:

Dict[str, Any]

_instance

Singleton instance of LoggingConfig

Type:

LoggingConfig

_config

Current active configuration

Type:

Dict[str, Any]

_initialized

Whether the configuration has been initialized

Type:

bool

_debug_mode

Whether to print debug messages during configuration

Type:

bool

Examples

# Initialize with default settings LoggingConfig.initialize()

# Initialize with a configuration file LoggingConfig.initialize(config_file=”logging.yaml”)

# Get a configuration value log_dir = LoggingConfig.get(“log_dir”)

DEFAULT_CONFIG = {'backup_count': 5, 'colored_console': True, 'datefmt': '%Y-%m-%d %H:%M:%S.%f', 'default_level': 'INFO', 'disable_rotation': False, 'exit_on_critical': False, 'log_dir': 'logs', 'log_filename': 'app', 'log_format': '%(asctime)s - %(filename)s - %(name)s - [%(levelname)s] - %(message)s', 'rotation_size_mb': 10, 'test_mode': False}
classmethod debug_print(message)[source]

Print debug message only if debug mode is enabled.

Parameters:

message (str) – The message to print when debugging is enabled

Return type:

None

classmethod initialize(config_file=None, use_cli_args=True, **kwargs)[source]

Initialize configuration from various sources using a two-phase approach.

The configuration is loaded in two phases: 1. Collection Phase: Gather and convert configurations from all sources 2. Application Phase: Apply configurations in priority order 3. Finalization Phase: Set the initialized flag

Parameters:
  • config_file (str | None) – Path to configuration file (YAML)

  • use_cli_args (bool) – Whether to parse command-line arguments

  • **kwargs (Any) – Direct configuration values (highest priority)

Returns:

The complete configuration dictionary

Return type:

Dict[str, Any]

Examples

# Basic initialization LoggingConfig.initialize()

# Initialize with a YAML config file LoggingConfig.initialize(config_file=”logging.yaml”)

# Initialize with direct override values LoggingConfig.initialize(log_level=”DEBUG”, colored_console=False)

classmethod load_from_file(config_path)[source]

Load and convert configuration from a YAML file.

This is a convenience method that loads raw configuration from a file and then converts the values to appropriate types.

Parameters:

config_path (str) – Path to the configuration file

Returns:

Dictionary with configuration values converted to appropriate types

Return type:

Dict[str, Any]

classmethod load_from_env()[source]

Load and convert configuration from environment variables.

This is a convenience method that loads raw configuration from environment variables and then converts the values to appropriate types.

Returns:

Dictionary with configuration values converted to appropriate types

Return type:

Dict[str, Any]

classmethod parse_cli_args()[source]

Parse command-line arguments for logging configuration.

Parses command-line arguments for logging configuration options. Only recognizes specific logging-related arguments and ignores other arguments that might be intended for the application.

Supported arguments:

–log-config, –log-conf: Path to logging configuration file –log-level, –logging-level: Default logging level –log-dir, –logging-dir: Directory for log files

Returns:

Dictionary of parsed command-line arguments with proper type conversion

Return type:

Dict[str, Any]

Note

This method uses argparse.parse_known_args() to avoid conflicts with application-specific command-line arguments.

classmethod get_config()[source]

Get the complete current configuration.

If the configuration hasn’t been initialized yet, this will initialize it with default values before returning.

Returns:

Dictionary containing all configuration values

Return type:

Dict[str, Any]

Example

`python config = LoggingConfig.get_config() print(f"Log directory: {config['log_dir']}") `

classmethod get(key, default=None)[source]

Get a specific configuration value.

Parameters:
  • key (str) – The configuration key to retrieve

  • default (Any | None) – Value to return if the key is not found

Returns:

The configuration value or the default if not found

Return type:

Any

Example

`python log_dir = LoggingConfig.get("log_dir") level = LoggingConfig.get("default_level", "INFO") `

classmethod set(key, value)[source]

Set or update a configuration value.

This allows runtime modification of configuration values. Changes will be reflected in any new loggers created after the change.

Supports nested keys with dot notation (e.g., “module_levels.my_module”).

Parameters:
  • key (str) – The configuration key to set

  • value (Any) – The value to assign to the key

Return type:

None

Example

>>> # Disable exiting on critical logs
>>> LoggingConfig.set("exit_on_critical", False)
>>>
>>> # Set module-specific log level
>>> LoggingConfig.set("module_levels.my_module", "DEBUG")
classmethod get_level(name=None, default_level=None)[source]

Get the numeric log level based on configuration priority.

This method determines the appropriate log level based on priority order: 1. Explicit level parameter (highest priority) 2. Logger-specific configuration from external_loggers 3. Default level from configuration

Parameters:
  • name (str | None) – Optional logger name to check for specific configuration

  • default_level (str | None) – Optional override for the default level

Returns:

The numeric logging level (from logging module constants)

Return type:

int

Examples

Get default level for application:

>>> default_level = LoggingConfig.get_level()

Get level for a specific module:

>>> requests_level = LoggingConfig.get_level("requests.packages.urllib3")

Override with explicit level:

>>> debug_level = LoggingConfig.get_level(default_level="DEBUG")
classmethod map_level(level)[source]

Map string log level to numeric level.

Converts string log level names to their corresponding numeric values from the logging module. If the level string is not recognized, defaults to logging.INFO.

Parameters:

level (str) – String log level (‘DEBUG’, ‘INFO’, etc.)

Returns:

The corresponding numeric logging level (from logging module constants)

Return type:

int

Example

`python debug_level = LoggingConfig.map_level("DEBUG")  # Returns 10 warn_level = LoggingConfig.map_level("WARNING")  # Returns 30 `

classmethod is_initialized()[source]

Check if logging configuration has been initialized.

Return type:

bool

classmethod reset()[source]

Reset configuration to default values.

This method restores all configuration settings to their default values, which is particularly useful for testing where each test needs to start with a clean configuration state.

Returns:

The LoggingConfig class for method chaining

Return type:

Type[LoggingConfig]

Example

`python # Reset to defaults and then set a specific value LoggingConfig.reset().set("colored_console", False) `

classmethod get_filename_prefix()[source]

Get the configured log filename prefix.

Returns:

The configured prefix string, defaulting to ‘app’.

Return type:

str

Configuration Class

class prismalog.config.LoggingConfig[source]

Bases: object

Configuration manager for prismalog package.

Handles loading configuration from multiple sources with a priority order: 1. Programmatic settings 2. Command-line arguments 3. Configuration files (YAML) 4. Environment variables (including GitHub Actions secrets) 5. Default values

This class uses a singleton pattern to ensure consistent configuration throughout the application lifecycle. It supports configuration from multiple sources and provides automatic type conversion.

Return type:

LoggingConfig

DEFAULT_CONFIG

Default configuration values

Type:

Dict[str, Any]

_instance

Singleton instance of LoggingConfig

Type:

LoggingConfig

_config

Current active configuration

Type:

Dict[str, Any]

_initialized

Whether the configuration has been initialized

Type:

bool

_debug_mode

Whether to print debug messages during configuration

Type:

bool

Examples

# Initialize with default settings LoggingConfig.initialize()

# Initialize with a configuration file LoggingConfig.initialize(config_file=”logging.yaml”)

# Get a configuration value log_dir = LoggingConfig.get(“log_dir”)

DEFAULT_CONFIG = {'backup_count': 5, 'colored_console': True, 'datefmt': '%Y-%m-%d %H:%M:%S.%f', 'default_level': 'INFO', 'disable_rotation': False, 'exit_on_critical': False, 'log_dir': 'logs', 'log_filename': 'app', 'log_format': '%(asctime)s - %(filename)s - %(name)s - [%(levelname)s] - %(message)s', 'rotation_size_mb': 10, 'test_mode': False}
classmethod debug_print(message)[source]

Print debug message only if debug mode is enabled.

Parameters:

message (str) – The message to print when debugging is enabled

Return type:

None

classmethod initialize(config_file=None, use_cli_args=True, **kwargs)[source]

Initialize configuration from various sources using a two-phase approach.

The configuration is loaded in two phases: 1. Collection Phase: Gather and convert configurations from all sources 2. Application Phase: Apply configurations in priority order 3. Finalization Phase: Set the initialized flag

Parameters:
  • config_file (str | None) – Path to configuration file (YAML)

  • use_cli_args (bool) – Whether to parse command-line arguments

  • **kwargs (Any) – Direct configuration values (highest priority)

Returns:

The complete configuration dictionary

Return type:

Dict[str, Any]

Examples

# Basic initialization LoggingConfig.initialize()

# Initialize with a YAML config file LoggingConfig.initialize(config_file=”logging.yaml”)

# Initialize with direct override values LoggingConfig.initialize(log_level=”DEBUG”, colored_console=False)

classmethod load_from_file(config_path)[source]

Load and convert configuration from a YAML file.

This is a convenience method that loads raw configuration from a file and then converts the values to appropriate types.

Parameters:

config_path (str) – Path to the configuration file

Returns:

Dictionary with configuration values converted to appropriate types

Return type:

Dict[str, Any]

classmethod load_from_env()[source]

Load and convert configuration from environment variables.

This is a convenience method that loads raw configuration from environment variables and then converts the values to appropriate types.

Returns:

Dictionary with configuration values converted to appropriate types

Return type:

Dict[str, Any]

classmethod parse_cli_args()[source]

Parse command-line arguments for logging configuration.

Parses command-line arguments for logging configuration options. Only recognizes specific logging-related arguments and ignores other arguments that might be intended for the application.

Supported arguments:

–log-config, –log-conf: Path to logging configuration file –log-level, –logging-level: Default logging level –log-dir, –logging-dir: Directory for log files

Returns:

Dictionary of parsed command-line arguments with proper type conversion

Return type:

Dict[str, Any]

Note

This method uses argparse.parse_known_args() to avoid conflicts with application-specific command-line arguments.

classmethod get_config()[source]

Get the complete current configuration.

If the configuration hasn’t been initialized yet, this will initialize it with default values before returning.

Returns:

Dictionary containing all configuration values

Return type:

Dict[str, Any]

Example

`python config = LoggingConfig.get_config() print(f"Log directory: {config['log_dir']}") `

classmethod get(key, default=None)[source]

Get a specific configuration value.

Parameters:
  • key (str) – The configuration key to retrieve

  • default (Any | None) – Value to return if the key is not found

Returns:

The configuration value or the default if not found

Return type:

Any

Example

`python log_dir = LoggingConfig.get("log_dir") level = LoggingConfig.get("default_level", "INFO") `

classmethod set(key, value)[source]

Set or update a configuration value.

This allows runtime modification of configuration values. Changes will be reflected in any new loggers created after the change.

Supports nested keys with dot notation (e.g., “module_levels.my_module”).

Parameters:
  • key (str) – The configuration key to set

  • value (Any) – The value to assign to the key

Return type:

None

Example

>>> # Disable exiting on critical logs
>>> LoggingConfig.set("exit_on_critical", False)
>>>
>>> # Set module-specific log level
>>> LoggingConfig.set("module_levels.my_module", "DEBUG")
classmethod get_level(name=None, default_level=None)[source]

Get the numeric log level based on configuration priority.

This method determines the appropriate log level based on priority order: 1. Explicit level parameter (highest priority) 2. Logger-specific configuration from external_loggers 3. Default level from configuration

Parameters:
  • name (str | None) – Optional logger name to check for specific configuration

  • default_level (str | None) – Optional override for the default level

Returns:

The numeric logging level (from logging module constants)

Return type:

int

Examples

Get default level for application:

>>> default_level = LoggingConfig.get_level()

Get level for a specific module:

>>> requests_level = LoggingConfig.get_level("requests.packages.urllib3")

Override with explicit level:

>>> debug_level = LoggingConfig.get_level(default_level="DEBUG")
classmethod map_level(level)[source]

Map string log level to numeric level.

Converts string log level names to their corresponding numeric values from the logging module. If the level string is not recognized, defaults to logging.INFO.

Parameters:

level (str) – String log level (‘DEBUG’, ‘INFO’, etc.)

Returns:

The corresponding numeric logging level (from logging module constants)

Return type:

int

Example

`python debug_level = LoggingConfig.map_level("DEBUG")  # Returns 10 warn_level = LoggingConfig.map_level("WARNING")  # Returns 30 `

classmethod is_initialized()[source]

Check if logging configuration has been initialized.

Return type:

bool

classmethod reset()[source]

Reset configuration to default values.

This method restores all configuration settings to their default values, which is particularly useful for testing where each test needs to start with a clean configuration state.

Returns:

The LoggingConfig class for method chaining

Return type:

Type[LoggingConfig]

Example

`python # Reset to defaults and then set a specific value LoggingConfig.reset().set("colored_console", False) `

classmethod get_filename_prefix()[source]

Get the configured log filename prefix.

Returns:

The configured prefix string, defaulting to ‘app’.

Return type:

str

Configuration Constants

LoggingConfig.DEFAULT_CONFIG = {'backup_count': 5, 'colored_console': True, 'datefmt': '%Y-%m-%d %H:%M:%S.%f', 'default_level': 'INFO', 'disable_rotation': False, 'exit_on_critical': False, 'log_dir': 'logs', 'log_filename': 'app', 'log_format': '%(asctime)s - %(filename)s - %(name)s - [%(levelname)s] - %(message)s', 'rotation_size_mb': 10, 'test_mode': False}