colorlog

raw JSON →
6.10.1 verified Tue May 12 auth: no python install: verified quickstart: verified

colorlog is a Python library that adds colors to the output of Python's standard logging module. It currently stands at version 6.10.1 and is in active maintenance, focusing on bug fixes and Python 3 compatibility, rather than major feature additions that might introduce breaking changes.

pip install colorlog
error ModuleNotFoundError: No module named 'colorlog'
cause The colorlog package has not been installed in the current Python environment or the environment where the script is being executed.
fix
Install the colorlog package using pip: pip install colorlog
error colorlog not showing colors
cause This issue often arises when the terminal or IDE console does not support ANSI escape codes, or when `logging.basicConfig()` is called before `colorlog` is imported and configured, preventing `colorlog` from properly wrapping stream handlers. On Windows, ensure colorama (a dependency of colorlog) is correctly initializing.
fix
Ensure colorlog is imported and its basicConfig (or ColoredFormatter on handlers) is applied *before* any logging.basicConfig() calls if you want it to manage the root logger. Verify your terminal supports ANSI escape codes (e.g., using a modern terminal or TERM=xterm-256color).
import colorlog
import logging

# Best practice: use colorlog.basicConfig directly
colorlog.basicConfig(level=logging.DEBUG,
                    format='%(log_color)s%(levelname)-8s%(reset)s %(message)s')

# Or, if you need to use logging.basicConfig first, then apply ColoredFormatter manually
# logging.basicConfig(level=logging.DEBUG)
# handler = colorlog.StreamHandler()
# handler.setFormatter(colorlog.ColoredFormatter('%(log_color)s%(levelname)-8s%(reset)s %(message)s'))
# logging.getLogger().addHandler(handler)

logger = logging.getLogger(__name__)
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
error colorlog raw escape codes in log file
cause When a `FileHandler` is configured to use `colorlog.ColoredFormatter`, the ANSI escape codes meant for terminal colorization are written directly into the plain text log file, making the file unreadable as it does not interpret these codes.
fix
Use a standard logging.Formatter for FileHandlers to ensure log files contain plain text, while continuing to use colorlog.ColoredFormatter for StreamHandlers (console output).
import colorlog
import logging

# Configure a logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Console handler with colors
console_handler = colorlog.StreamHandler()
console_formatter = colorlog.ColoredFormatter(
    '%(log_color)s%(levelname)-8s%(reset)s %(message)s',
    log_colors={
        'DEBUG': 'cyan',
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'red,bg_white',
    }
)
console_handler.setFormatter(console_formatter)
logger.addHandler(console_handler)

# File handler without colors
file_handler = logging.FileHandler('app.log')
file_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
file_handler.setFormatter(file_formatter)
logger.addHandler(file_handler)

logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
breaking colorlog v6.x dropped support for Python 2 and Python versions older than 3.6. Users needing compatibility with older Python versions (e.g., Python 2.x or 3.5) must pin their dependency to `colorlog<5` or `colorlog<6` respectively.
fix Upgrade Python to 3.6+ or pin `colorlog<5` for Python 2.x or `colorlog<6` for Python 3.5.
breaking The internal `TTYColoredFormatter` class was merged into `ColoredFormatter` in version 6.0.0-alpha.2. Direct references to `TTYColoredFormatter` will no longer work.
fix Replace `TTYColoredFormatter` with `ColoredFormatter`.
gotcha Logging output redirected to a file or a non-terminal environment will include raw ANSI escape codes, making the file unreadable unless processed by an ANSI-aware viewer. colorlog attempts to detect terminal capabilities but might fail in some setups.
fix Ensure `ColoredFormatter` is only used with handlers outputting to terminals (e.g., `logging.StreamHandler`). For file logging, use a standard `logging.Formatter` or configure distinct handlers for terminal vs. file output. You can also use the `no_color` argument or the `NO_COLOR` environment variable to disable colors.
gotcha The `FORCE_COLOR` environment variable can override color detection, forcing colors even if `colorlog` thinks it's not a TTY. Conversely, the `NO_COLOR` environment variable (following the no-color.org standard) can disable colors.
fix Be aware of these environment variables when troubleshooting unexpected color behavior in different environments.
deprecated The internal module `colorlog.colorlog` was renamed to `colorlog.formatter`. While direct import from `colorlog.colorlog` might still work for some time due to internal mechanisms, it is considered an internal detail and should not be relied upon.
fix Always import `ColoredFormatter` directly from the top-level `colorlog` package (e.g., `from colorlog import ColoredFormatter`).
python os / libc status wheel install import disk
3.10 alpine (musl) - - 0.03s 17.8M
3.10 slim (glibc) - - 0.02s 18M
3.11 alpine (musl) - - 0.06s 19.7M
3.11 slim (glibc) - - 0.05s 20M
3.12 alpine (musl) - - 0.04s 11.6M
3.12 slim (glibc) - - 0.04s 12M
3.13 alpine (musl) - - 0.04s 11.2M
3.13 slim (glibc) - - 0.04s 12M
3.9 alpine (musl) - - 0.04s 17.3M
3.9 slim (glibc) - - 0.02s 18M

This example demonstrates how to set up a basic logger with `colorlog.ColoredFormatter` to get colorized output. It defines custom colors for different logging levels and then logs messages at various severities. Alternatively, for a simpler setup, `colorlog.basicConfig()` can be used, which internally sets up a `ColoredFormatter` for the root logger.

import logging
import colorlog

# Configure a ColoredFormatter
formatter = colorlog.ColoredFormatter(
    '%(log_color)s%(levelname)-8s%(reset)s %(blue)s%(message)s',
    datefmt=None,
    reset=True,
    log_colors={
        'DEBUG':    'cyan',
        'INFO':     'green',
        'WARNING':  'yellow',
        'ERROR':    'red',
        'CRITICAL': 'red,bg_white'
    },
    secondary_log_colors={},
    style='%'
)

# Get the root logger and set its level
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

# Add a StreamHandler with the colored formatter
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)

# Example log messages
logger.debug('This is a debug message')
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.error('This is an error message')
logger.critical('This is a critical message')