colorlog
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.
Warnings
- 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.
- breaking The internal `TTYColoredFormatter` class was merged into `ColoredFormatter` in version 6.0.0-alpha.2. Direct references to `TTYColoredFormatter` will no longer work.
- 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.
- 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.
- 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.
Install
-
pip install colorlog
Imports
- basicConfig
import colorlog colorlog.basicConfig(...)
- ColoredFormatter
from colorlog import ColoredFormatter
Quickstart
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')