Logger

The logger module, located at pyutils.logger, provides a standardized logging utility that can be used across various applications to ensure consistent and effective logging practices. It leverages Python’s built-in logging module to create a configurable logger that can be easily integrated into different projects.

This implementation provides a unified logging interface that supports customizable handlers, formatters, and log levels, enabling seamless logging to various outputs like the console, files, or external services.

Implementation

The logger utility is implemented through the following primary class:

class Logger

Bases: object

__init__(name, level=10)

Creates a new logger instance with the specified name and configures it according to the provided parameters. Sets up file and/or console handlers as requested.

Parameters:
  • name (str) – Unique identifier for this logger instance. Should be descriptive of the component or module using the logger. Required

  • log_to_file (bool) – Whether to enable file output. When True, log messages will be written to the specified log file with timestamp formatting. Default is True.

  • log_to_stream (bool) – Whether to enable console output. When True, log messages will be displayed in the console with rich formatting and error messages will include filtered tracebacks. Default is True.

  • log_file (str) – Path to the log file for file output. Can be relative or absolute. Parent directories will be created if they don’t exist. Default is ‘app.log’.

  • level (int) – Minimum log level to handle. Uses standard logging module constants (DEBUG=10, INFO=20, WARNING=30, ERROR=40, CRITICAL=50). Default is logging.DEBUG.

Raises:
  • PermissionError – If the log file cannot be created or written to.

  • FileNotFoundError – If the log file directory doesn’t exist and cannot be created.

add_console_handler(richFormatting=True)

Add a console handler to the logger to enable console output.

Parameters:

richFormatting (bool) – If True, uses rich formatting for console output. If False, uses standard logging formatting. Default is True.

Example

>>> logger.add_console_handler(richFormatting=True)
add_file_handler(log_file='app.log', dir='.')

Add a file handler to the logger to enable file output.

Parameters:
  • log_file (str) – Path to the log file where messages will be written. Can be relative or absolute. Parent directories will be created if they don’t exist. Default is ‘app.log’.

  • dir (str) – Directory where the log file is located. Default is the current directory.

Raises:
  • PermissionError – If the log file cannot be created or written to.

  • FileNotFoundError – If the log file directory doesn’t exist and cannot be created.

Example

>>> logger.add_file_handler(log_file="logs/my_app.log")
add_handler(handler)

Add a custom logging handler to the logger.

Parameters:

handler (logging.Handler) – An instance of a logging handler (e.g., StreamHandler, FileHandler, or a custom handler) to add to the logger.

Example

>>> custom_handler = logging.StreamHandler()
>>> logger.add_handler(custom_handler)
critical(msg)

Log a critical error message for severe application failures. Critical messages indicate very serious errors that may cause the application to abort or become unstable. These represent the highest severity level and typically require immediate attention.

Parameters:

msg – The critical error message to log. Should clearly describe the severe problem and its potential impact on the application.

Example

>>> logger.critical("Database connection pool exhausted - application stopping")
>>> logger.critical("Out of memory: cannot continue processing")
debug(msg)

Log a debug message for detailed troubleshooting information. Debug messages are typically used for detailed diagnostic information that is only of interest when diagnosing problems.

Parameters:

msg – The debug message to log. Should be descriptive enough to help with troubleshooting but not overly verbose.

Example

>>> logger.debug("Processing user input: username='john_doe'")
>>> logger.debug("Database query returned 42 results")
error(msg)

Log an error message and optionally print a filtered traceback. Error messages indicate that a serious problem occurred that prevented the application from performing a function.

Parameters:

msg – The error message to log. Should clearly describe what went wrong and provide context for debugging.

Example

>>> try:
...     result = divide(10, 0)
... except ZeroDivisionError:
...     logger.error("Division by zero occurred in calculation")
info(msg)

Log an informational message about normal application flow. Info messages are used to record normal application behavior and significant events that confirm the application is working as expected.

Parameters:

msg – The informational message to log. Should describe what the application is doing or what event occurred.

Example

>>> logger.info("User 'john_doe' logged in successfully")
>>> logger.info("Application started successfully")
warning(msg)

Log a warning message for potentially problematic situations. Warning messages indicate that something unexpected happened or might happen, but the application is still working as expected. They signal potential issues that should be monitored or addressed.

Parameters:

msg – The warning message to log. Should clearly describe what condition triggered the warning and any potential implications.

Example

>>> logger.warning("API rate limit approaching: 80% of quota used")
>>> logger.warning("Configuration file not found, using defaults")

Examples

Below an example where you create a logger instance, add handlers, and log messages at various levels:

from pyutils.logger import Logger

# Create a logger instance
logger = Logger(name="my_logger", level="DEBUG")
logger.add_console_handler()
logger.add_file_handler("app.log")

# Log messages at various levels
logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warning("This is a warning message.")
logger.error("This is an error message.")