CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-colorlog

Add colours to the output of Python's logging module with ANSI escape codes and terminal support.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

colors.mddocs/

Color System

ANSI escape code generation and color parsing system. Provides comprehensive color support including foreground/background colors, text styling, and 256-color terminal support.

Capabilities

Color Parsing

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")

Escape Codes Dictionary

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 formatting
  • bold: Bold/bright text
  • thin: Thin text (terminal dependent)

Foreground Colors:

  • Basic colors: black, red, green, yellow, blue, purple, cyan, white
  • Light colors: light_black, light_red, light_green, light_yellow, light_blue, light_purple, light_cyan, light_white
  • With bold: bold_black, bold_red, etc.
  • With thin: thin_black, thin_red, etc.
  • With prefix: fg_black, fg_red, etc.

Background Colors:

  • Basic: bg_black, bg_red, bg_green, bg_yellow, bg_blue, bg_purple, bg_cyan, bg_white
  • Light: bg_light_black, bg_light_red, etc.

256-Color Support:

  • Foreground: fg_0 through fg_255
  • Background: bg_0 through bg_255

Usage 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 Log Colors

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)

Color Names Reference

Standard Colors

Basic Colors:

  • black, red, green, yellow, blue, purple, cyan, white

Light/Bright Colors:

  • light_black, light_red, light_green, light_yellow
  • light_blue, light_purple, light_cyan, light_white

Color Combinations

Colors 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 text

Format Styles

Colors 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}"

Platform Support

Windows Support

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)

Terminal Detection

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
)

Environment Variables

  • NO_COLOR: Disable color output when set
  • FORCE_COLOR: Force color output when set (overrides NO_COLOR)

Internal Color Generation

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[41m

This ensures consistent ANSI escape code generation across all supported colors and styles.

Install with Tessl CLI

npx tessl i tessl/pypi-colorlog

docs

colors.md

formatters.md

index.md

logging-functions.md

tile.json