hbutils.logging.format
Colored logging formatter utilities with ANSI styling and multi-line alignment.
This module provides utilities for enhancing Python logging output using ANSI escape sequences. It includes a color palette class for terminal styling, a formatter that applies color based on log severity, and a helper function for aligning multi-line log messages with the log prefix.
The main public components are:
ANSIColors- ANSI escape sequences for colors and styles.ColoredFormatter- Logging formatter with colorized output.format_multiline_message()- Indentation helper for multi-line messages.
Note
ANSI escape codes are intended for terminal output. Some environments (such as Windows cmd without ANSI support or log files) may not render colors correctly.
Example:
>>> import logging
>>> from hbutils.logging.format import ColoredFormatter
>>>
>>> logger = logging.getLogger("example")
>>> logger.setLevel(logging.DEBUG)
>>> handler = logging.StreamHandler()
>>> handler.setFormatter(ColoredFormatter())
>>> logger.addHandler(handler)
>>>
>>> logger.info("Single line message")
>>> logger.warning("Multi-line message:\nLine 2\nLine 3")
__all__
- hbutils.logging.format.__all__ = ['ANSIColors', 'ColoredFormatter', 'format_multiline_message']
Built-in mutable sequence.
If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.
ANSIColors
- class hbutils.logging.format.ANSIColors[source]
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.
- Variables:
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 a compatible terminal >>> print(f"{ANSIColors.BOLD}{ANSIColors.GREEN}Bold green text{ANSIColors.RESET}") Bold green text # Displayed in bold green
ColoredFormatter
- class hbutils.logging.format.ColoredFormatter(datefmt: str = '%Y-%m-%d %H:%M:%S', *args, **kwargs)[source]
Logging formatter with ANSI colors and multi-line alignment.
The formatter applies a color scheme based on log severity and ensures multi-line messages are indented to align with the log message content.
Color scheme:
DEBUG: Blue
INFO: Green
WARNING: Yellow
ERROR: Red
CRITICAL: Bold Red
- Variables:
COLORS (dict) – Mapping of log level names to ANSI color codes.
datefmt (str) – Date format string for timestamp rendering.
_indent_cache (dict) – Cached prefix lengths for indentation calculation.
Example:
>>> import logging >>> logger = logging.getLogger("demo") >>> handler = logging.StreamHandler() >>> handler.setFormatter(ColoredFormatter()) >>> logger.addHandler(handler) >>> logger.setLevel(logging.DEBUG) >>> logger.warning("Warning message\nwith multiple lines")
- __init__(datefmt: str = '%Y-%m-%d %H:%M:%S', *args, **kwargs)[source]
Initialize the formatter.
- Parameters:
datefmt (str) – Date format string for timestamps, defaults to
'%Y-%m-%d %H:%M:%S'.args – Additional positional arguments passed to
logging.Formatter.kwargs – Additional keyword arguments passed to
logging.Formatter.
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 with color and indentation.
Output structure:
[timestamp] level_name logger_name messageMulti-line messages are indented so that continuation lines align with the first character of the message content.
- Parameters:
record (logging.LogRecord) – The log record to format.
- Returns:
The formatted log message as a string.
- 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) >>> print(formatted) [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 indentation for continuation lines.
The first line of the message is preserved, while each subsequent line is prefixed with a number of spaces specified by
indent_length. This function is commonly used to align multi-line log messages with a log prefix.- Parameters:
message (str) – The message to format, potentially containing multiple lines.
indent_length (int) – Number of spaces to indent continuation lines.
- Returns:
The formatted message with indentation applied to continuation lines.
- 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