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

logging-functions.mddocs/

Enhanced Logging Functions

Wrapper functions that enhance Python's standard logging functions with automatic configuration and colored output. These functions automatically set up ColoredFormatter when no handlers exist.

Capabilities

Basic Configuration

Enhanced version of logging.basicConfig that automatically uses ColoredFormatter.

def basicConfig(
    style: str = "%", 
    log_colors: Optional[LogColors] = None,
    reset: bool = True,
    secondary_log_colors: Optional[SecondaryLogColors] = None,
    format: str = "%(log_color)s%(levelname)s%(reset)s:%(name)s:%(message)s",
    datefmt: Optional[str] = None,
    **kwargs
) -> None:
    """
    Call logging.basicConfig and override the formatter it creates.

    Parameters:
    - 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
    - format: Log format string with color support
    - datefmt: Date format string
    - **kwargs: Additional arguments passed to logging.basicConfig
    """

Usage Example:

import colorlog

# Simple setup with defaults
colorlog.basicConfig()

# Custom setup
colorlog.basicConfig(
    format='%(log_color)s%(levelname)-8s%(reset)s %(message)s',
    log_colors={
        'DEBUG': 'cyan',
        'INFO': 'green',
        'WARNING': 'yellow', 
        'ERROR': 'red',
        'CRITICAL': 'bold_red',
    },
    level=logging.DEBUG
)

Enhanced Logging Functions

Wrapper functions that automatically configure colored logging if no handlers exist.

def debug(msg, *args, **kwargs):
    """
    Log a message with severity 'DEBUG' on the root logger.
    Automatically configures colored logging if needed.
    """

def info(msg, *args, **kwargs):
    """
    Log a message with severity 'INFO' on the root logger.
    Automatically configures colored logging if needed.
    """

def warning(msg, *args, **kwargs):
    """
    Log a message with severity 'WARNING' on the root logger.
    Automatically configures colored logging if needed.
    """

def error(msg, *args, **kwargs):
    """
    Log a message with severity 'ERROR' on the root logger.
    Automatically configures colored logging if needed.
    """

def critical(msg, *args, **kwargs):
    """
    Log a message with severity 'CRITICAL' on the root logger.
    Automatically configures colored logging if needed.
    """

def log(level, msg, *args, **kwargs):
    """
    Log 'msg % args' with the integer severity 'level' on the root logger.
    Automatically configures colored logging if needed.
    """

def exception(msg, *args, **kwargs):
    """
    Log a message with severity 'ERROR' on the root logger, with exc_info
    which is used to include the current exception in the log message.
    Automatically configures colored logging if needed.
    """

Usage Example:

import colorlog

# These functions will automatically set up colored logging
colorlog.debug("Debug message")
colorlog.info("Info message") 
colorlog.warning("Warning message")
colorlog.error("Error message")
colorlog.critical("Critical message")

# Log with custom level
colorlog.log(25, "Custom level message")

# Log exception with traceback
try:
    1 / 0
except:
    colorlog.exception("An error occurred")

Re-exported Logging Objects

Standard logging objects re-exported for convenience.

# Logger creation and management
def getLogger(name: Optional[str] = None) -> logging.Logger:
    """Return a logger with the specified name or root logger if None."""

# Handler class
class StreamHandler(logging.StreamHandler):
    """Stream handler for logging output."""

# Root logger instance
root: logging.Logger

Usage Example:

import colorlog

# Get a named logger
logger = colorlog.getLogger('myapp')

# Use StreamHandler directly
handler = colorlog.StreamHandler()
formatter = colorlog.ColoredFormatter()
handler.setFormatter(formatter)
logger.addHandler(handler)

# Access root logger
colorlog.root.setLevel(logging.DEBUG)

Log Level Constants

Standard logging level constants re-exported for convenience.

# Log level constants
CRITICAL: int   # 50
DEBUG: int      # 10  
ERROR: int      # 40
FATAL: int      # 50 (alias for CRITICAL)
INFO: int       # 20
NOTSET: int     # 0
WARN: int       # 30 (deprecated alias for WARNING)
WARNING: int    # 30

Usage Example:

import colorlog

# Set log levels using constants
logger = colorlog.getLogger('example')
logger.setLevel(colorlog.DEBUG)

# Use in conditional logging
if logger.isEnabledFor(colorlog.WARNING):
    logger.warning("This is a warning")

Automatic Configuration

The enhanced logging functions use a decorator that automatically calls basicConfig() with default colored formatting if no handlers exist on the root logger. This provides immediate colored output without manual setup.

Internal Implementation:

def ensure_configured(func):
    """Modify a function to call basicConfig() first if no handlers exist."""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        if len(logging.root.handlers) == 0:
            basicConfig()
        return func(*args, **kwargs)
    return wrapper

This ensures that colorlog functions work out-of-the-box while maintaining compatibility with existing logging configurations.

Configuration Methods

Dictionary Configuration

import logging.config

logging.config.dictConfig({
    'formatters': {
        'colored': {
            '()': 'colorlog.ColoredFormatter',
            'format': "%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s"
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'colored'
        }
    },
    'root': {
        'handlers': ['console'],
        'level': 'DEBUG'
    }
})

File Configuration

[formatters]
keys=color

[formatter_color]
class=colorlog.ColoredFormatter
format=%(log_color)s%(levelname)-8s%(reset)s %(bg_blue)s[%(name)s]%(reset)s %(message)s
datefmt=%m-%d %H:%M:%S

Install with Tessl CLI

npx tessl i tessl/pypi-colorlog

docs

colors.md

formatters.md

index.md

logging-functions.md

tile.json