hbutils.logging.format
- Overview:
This module provides functionality to enhance logging output with colors for different log levels. It includes an ANSIColors class defining ANSI escape sequences for various colors and styles, and a ColoredFormatter class to format log messages with these colors based on their severity level.
The module supports multi-line log messages with proper indentation alignment, making logs more readable and visually organized.
- Example::
>>> import logging >>> from hbutils.logging import ColoredFormatter >>> >>> logger = logging.getLogger() >>> logger.setLevel(logging.DEBUG) >>> console_handler = logging.StreamHandler() >>> console_handler.setFormatter(ColoredFormatter()) >>> logger.addHandler(console_handler) >>> >>> # Test single line message >>> logger.info("This is a single line message") >>> # Test multi-line message >>> logger.warning("This is a multi-line message:\nLine 2 content\nLine 3 content\nLine 4 content") >>> logger.error( ... "Error details:\n - Error code: 500\n - Error message: Internal server error\n - Stack trace follows...")
ANSIColors
- class hbutils.logging.format.ANSIColors[source]
A collection of ANSI escape sequences for terminal text coloring and styling.
These constants can be used to format strings with various colors and text styles in terminal environments that support ANSI escape codes.
- Attributes:
RESET (str): Reset all text formatting to default.
BOLD (str): Apply bold text style.
UNDERLINE (str): Apply underline text style.
BLACK (str): Apply black color to text.
RED (str): Apply red color to text.
GREEN (str): Apply green color to text.
YELLOW (str): Apply yellow color to text.
BLUE (str): Apply blue color to text.
MAGENTA (str): Apply magenta color to text.
CYAN (str): Apply cyan color to text.
WHITE (str): Apply white color to text.
BRIGHT_BLACK (str): Apply bright black (gray) color to text.
BRIGHT_RED (str): Apply bright red color to text.
BRIGHT_GREEN (str): Apply bright green color to text.
BRIGHT_YELLOW (str): Apply bright yellow color to text.
BRIGHT_BLUE (str): Apply bright blue color to text.
BRIGHT_MAGENTA (str): Apply bright magenta color to text.
BRIGHT_CYAN (str): Apply bright cyan color to text.
BRIGHT_WHITE (str): Apply bright white color to text.
- Example::
>>> print(f"{ANSIColors.RED}This is red text{ANSIColors.RESET}") This is red text # (displayed in red in terminal) >>> print(f"{ANSIColors.BOLD}{ANSIColors.GREEN}Bold green text{ANSIColors.RESET}") Bold green text # (displayed in bold green in terminal)
ColoredFormatter
- class hbutils.logging.format.ColoredFormatter(datefmt: str = '%Y-%m-%d %H:%M:%S', *args, **kwargs)[source]
A logging formatter that applies colors to log messages based on their severity level.
This formatter enhances log readability by applying different colors to different log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL) and formatting components (timestamp, level name, logger name, message). It also supports multi-line messages with proper indentation alignment.
- The color scheme is:
DEBUG: Blue
INFO: Green
WARNING: Yellow
ERROR: Red
CRITICAL: Bold Red
- Attributes:
COLORS (dict): Mapping of log level names to their corresponding ANSI color codes. datefmt (str): The date format string for timestamps.
- Example::
>>> import logging >>> logger = logging.getLogger(__name__) >>> handler = logging.StreamHandler() >>> handler.setFormatter(ColoredFormatter()) >>> logger.addHandler(handler) >>> logger.setLevel(logging.DEBUG) >>> >>> logger.debug("Debug message") >>> logger.info("Info message") >>> logger.warning("Warning message\nwith multiple lines") >>> logger.error("Error message") >>> logger.critical("Critical message")
- __init__(datefmt: str = '%Y-%m-%d %H:%M:%S', *args, **kwargs)[source]
Initialize the ColoredFormatter with custom date format and optional parameters.
- Parameters:
datefmt (str) – The date format string for formatting timestamps in log messages. Defaults to ‘%Y-%m-%d %H:%M:%S’.
args – Additional positional arguments passed to the parent Formatter class.
kwargs – Additional keyword arguments passed to the parent Formatter class.
- Example::
>>> formatter = ColoredFormatter(datefmt='%H:%M:%S') >>> formatter = ColoredFormatter(datefmt='%Y/%m/%d %H:%M:%S')
- format(record: LogRecord) str[source]
Format the specified log record as colored text with proper multi-line indentation.
This method applies appropriate colors based on the log level and formats the message with the following structure: [timestamp] level_name logger_name message
Multi-line messages are automatically indented so that continuation lines align with the start of the message content.
- Parameters:
record (logging.LogRecord) – The log record to be formatted.
- Returns:
The formatted log message with appropriate colors and proper multi-line indentation.
- Return type:
str
- Example::
>>> import logging >>> record = logging.LogRecord( ... name='test', level=logging.INFO, pathname='', lineno=0, ... msg='Multi-line\nmessage', args=(), exc_info=None ... ) >>> formatter = ColoredFormatter() >>> formatted = formatter.format(record) >>> # Output will be colored and properly indented: >>> # [2024-01-15 10:30:45] INFO test Multi-line >>> # message
format_multiline_message
- hbutils.logging.format.format_multiline_message(message: str, indent_length: int) str[source]
Format a multi-line message with proper indentation for continuation lines.
The first line of the message remains unchanged, while all subsequent lines are indented by the specified number of spaces to align with the message content.
- Parameters:
message (str) – The message to format, potentially containing multiple lines.
indent_length (int) – The number of spaces to indent continuation lines.
- Returns:
The formatted message with proper indentation for multi-line content.
- Return type:
str
- Example::
>>> msg = "First line\nSecond line\nThird line" >>> result = format_multiline_message(msg, 4) >>> print(result) First line Second line Third line