Add colours to the output of Python's logging module with ANSI escape codes and terminal support.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core formatting classes that add color support to log messages. These formatters extend Python's standard logging.Formatter with ANSI color codes for enhanced terminal output.
Main formatter class that allows colors to be placed in the format string. Extends logging.Formatter with color support through ANSI escape codes.
from typing import IO, Dict, Mapping, Any, Optional, Literal
class ColoredFormatter(logging.Formatter):
def __init__(
self,
fmt: Optional[str] = None,
datefmt: Optional[str] = None,
style: Literal["%", "{", "$"] = "%",
log_colors: Optional[LogColors] = None,
reset: bool = True,
secondary_log_colors: Optional[SecondaryLogColors] = None,
validate: bool = True,
stream: Optional[IO[str]] = None,
no_color: bool = False,
force_color: bool = False,
defaults: Optional[Dict[str, Any]] = None,
):
"""
Set the format and colors the ColoredFormatter will use.
Parameters:
- fmt: Format string to use (uses default if None)
- datefmt: Date format string
- style: Format style ('%', '{', or '$')
- log_colors: Mapping of log level names to color names
- reset: Implicitly append color reset to all records
- secondary_log_colors: Map secondary log_color attributes
- validate: Validate the format string
- stream: Stream for TTY detection and color control
- no_color: Disable color output
- force_color: Enable color output (overrides no_color)
- defaults: Default values mapping (Python 3.10+)
"""
def formatMessage(self, record: logging.LogRecord) -> str:
"""Format a message from a record object."""Usage Example:
import colorlog
import logging
formatter = colorlog.ColoredFormatter(
'%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s',
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red,bg_white',
}
)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger('example')
logger.addHandler(handler)Extension of ColoredFormatter that uses per-level format strings. Allows different formatting for each log level.
from typing import Dict, Any, Mapping
class LevelFormatter:
def __init__(self, fmt: Mapping[str, str], **kwargs: Any):
"""
Configure a ColoredFormatter with its own format string for each log level.
Parameters:
- fmt: Mapping of log levels to format strings
- **kwargs: Additional arguments passed to ColoredFormatter
"""
def format(self, record: logging.LogRecord) -> str:
"""Format a record using the appropriate level-specific formatter."""Usage Example:
import colorlog
formatter = colorlog.LevelFormatter(
fmt={
"DEBUG": "%(log_color)s%(message)s (%(module)s:%(lineno)d)",
"INFO": "%(log_color)s%(message)s",
"WARNING": "%(log_color)sWRN: %(message)s (%(module)s:%(lineno)d)",
"ERROR": "%(log_color)sERR: %(message)s (%(module)s:%(lineno)d)",
"CRITICAL": "%(log_color)sCRT: %(message)s (%(module)s:%(lineno)d)",
},
log_colors={
'DEBUG': 'white',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
)Backward compatibility alias for ColoredFormatter. The features provided by this subclass are now included directly in the ColoredFormatter class.
TTYColoredFormatter = ColoredFormatterWhen using ColoredFormatter, these variables are available in format strings:
%(log_color)s: Color associated with the record's level%(reset)s: Color reset code%(<name>_log_color)s: Secondary colors based on secondary_log_colors configuration%(levelname)s, %(name)s, %(message)s, etc.Secondary log colors allow multiple color attributes based on log level. Each key in secondary_log_colors adds a {key}_log_color attribute.
Example:
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s %(message_log_color)s%(message)s",
secondary_log_colors={
'message': {
'ERROR': 'red',
'CRITICAL': 'red'
}
}
)The formatter automatically detects terminal capabilities and environment variables:
# Type aliases used in formatter signatures
from typing import Mapping
EscapeCodes = Mapping[str, str]
LogColors = Mapping[str, str]
SecondaryLogColors = Mapping[str, LogColors]Install with Tessl CLI
npx tessl i tessl/pypi-colorlog