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
ANSI escape code generation and color parsing system. Provides comprehensive color support including foreground/background colors, text styling, and 256-color terminal support.
Parse comma-separated color sequence strings into ANSI escape codes.
# Import from colorlog.escape_codes module
from colorlog.escape_codes import parse_colors
def parse_colors(string: str) -> str:
"""
Return escape codes from a color sequence string.
Parameters:
- string: Comma-separated color names (e.g., "red,bold" or "blue,bg_white")
Returns:
- str: Combined ANSI escape codes
"""Usage Example:
from colorlog.escape_codes import parse_colors
# Parse single color
red_code = parse_colors("red")
print(f"{red_code}This is red text\033[0m")
# Parse multiple colors
bold_red_on_white = parse_colors("bold_red,bg_white")
print(f"{bold_red_on_white}Bold red text on white background\033[0m")
# Parse complex combinations
style = parse_colors("bold,blue,bg_yellow")
print(f"{style}Bold blue text on yellow background\033[0m")Complete mapping of color names to ANSI escape codes.
# Import from colorlog.escape_codes module
from colorlog.escape_codes import escape_codes
from typing import Dict
escape_codes: Dict[str, str]The escape_codes dictionary contains all available color and formatting codes:
Basic Formatting:
reset: Clear all formattingbold: Bold/bright textthin: Thin text (terminal dependent)Foreground Colors:
black, red, green, yellow, blue, purple, cyan, whitelight_black, light_red, light_green, light_yellow, light_blue, light_purple, light_cyan, light_whitebold_black, bold_red, etc.thin_black, thin_red, etc.fg_black, fg_red, etc.Background Colors:
bg_black, bg_red, bg_green, bg_yellow, bg_blue, bg_purple, bg_cyan, bg_whitebg_light_black, bg_light_red, etc.256-Color Support:
fg_0 through fg_255bg_0 through bg_255Usage Example:
from colorlog.escape_codes import escape_codes
# Access individual escape codes
print(f"{escape_codes['red']}Red text{escape_codes['reset']}")
print(f"{escape_codes['bold_blue']}Bold blue text{escape_codes['reset']}")
print(f"{escape_codes['bg_yellow']}Yellow background{escape_codes['reset']}")
# 256-color support
print(f"{escape_codes['fg_196']}Bright red (256-color){escape_codes['reset']}")
print(f"{escape_codes['bg_21']}Blue background (256-color){escape_codes['reset']}")Default color mapping for log levels used by ColoredFormatter.
# Import from colorlog.formatter module
from colorlog.formatter import default_log_colors
from typing import Dict
default_log_colors: Dict[str, str] = {
"DEBUG": "white",
"INFO": "green",
"WARNING": "yellow",
"ERROR": "red",
"CRITICAL": "bold_red",
}Usage Example:
from colorlog.formatter import default_log_colors
import colorlog
# Use default colors
formatter = colorlog.ColoredFormatter(
log_colors=default_log_colors
)
# Customize based on defaults
custom_colors = default_log_colors.copy()
custom_colors["DEBUG"] = "cyan"
custom_colors["CRITICAL"] = "red,bg_white"
formatter = colorlog.ColoredFormatter(log_colors=custom_colors)Basic Colors:
black, red, green, yellow, blue, purple, cyan, whiteLight/Bright Colors:
light_black, light_red, light_green, light_yellowlight_blue, light_purple, light_cyan, light_whiteColors can be combined with commas in color specifications:
# Multiple effects
"bold,red" # Bold red text
"red,bg_white" # Red text on white background
"bold,blue,bg_yellow" # Bold blue text on yellow background
"thin,green" # Thin green textColors work with all Python logging format styles:
Percent Style (%):
"%(log_color)s%(levelname)s%(reset)s: %(message)s"Brace Style ({}):
"{log_color}{levelname}{reset}: {message}"Dollar Style ($):
"${log_color}${levelname}${reset}: ${message}"Colorlog automatically detects Windows and initializes colorama for ANSI color support:
# Automatic Windows setup (internal)
import sys
try:
import colorama
except ImportError:
pass
else:
if sys.platform == "win32":
colorama.init(strip=False)Colors are automatically disabled for non-TTY streams unless forced:
formatter = colorlog.ColoredFormatter(
stream=sys.stdout, # TTY detection
no_color=False, # Respect NO_COLOR env var
force_color=False # Force colors regardless of TTY
)The escape codes are generated programmatically using internal helper functions:
# Internal helper function (from colorlog.escape_codes module)
def esc(*codes: int) -> str:
"""
Generate ANSI escape sequence from numeric codes.
Parameters:
- codes: Variable number of ANSI numeric codes
Returns:
- str: Complete ANSI escape sequence
"""
return "\033[" + ";".join(str(code) for code in codes) + "m"
# Internal color code dictionaries
escape_codes_foreground: Dict[str, int]
escape_codes_background: Dict[str, int]Usage Example:
from colorlog.escape_codes import esc
# Generate custom escape codes
red_code = esc(31) # \033[31m
bold_red_code = esc(1, 31) # \033[1;31m
bg_red_code = esc(41) # \033[41mThis ensures consistent ANSI escape code generation across all supported colors and styles.
Install with Tessl CLI
npx tessl i tessl/pypi-colorlog