下面我将从简单方法到高级自定义,为你详细介绍如何在 Python 中实现日志颜色化。
使用 colorlog 库(最简单、推荐)
这是最直接、最简单的方法。colorlog 库专门为 Python 的 logging 模块设计,可以让你用最少的代码实现彩色日志。
安装
你需要安装这个库:
pip install colorlog
基本使用
colorlog 的核心是 colorlog.ColoredFormatter,你只需要用它来创建一个 Formatter,然后把它设置到你的 Handler 上即可。
import logging
import colorlog
# 1. 创建一个 logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # 设置日志级别
# 2. 创建一个 StreamHandler (用于输出到控制台)
handler = logging.StreamHandler()
# 3. 创建一个 ColoredFormatter
# %(log_color)s 是一个特殊的占位符,colorlog 会自动替换为 ANSI 颜色代码
# %(reset)s 用于重置颜色,避免影响后续输出
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(levelname)-8s%(reset)s | %(log_color)s%(message)s%(reset)s",
log_colors={
'DEBUG': 'cyan', # 青色
'INFO': 'green', # 绿色
'WARNING': 'yellow', # 黄色
'ERROR': 'red', # 红色
'CRITICAL': 'bold_red', # 加粗红色
}
)
# 4. 将 formatter 设置到 handler
handler.setFormatter(formatter)
# 5. 将 handler 添加到 logger
logger.addHandler(handler)
# 6. 输出日志
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.")
输出效果:
DEBUG | This is a debug message.
INFO | This is an info message.
WARNING | This is a warning message.
ERROR | This is an error message.
CRITICAL | This is a critical message.
(在你的终端中,这些文字会分别以青色、绿色、黄色、红色和加粗红色显示)
自定义格式
你可以像使用普通 logging.Formatter 一样,自由组合格式化字符串,加入时间戳:
formatter = colorlog.ColoredFormatter(
"%(log_color)s%(asctime)s - %(levelname)-8s%(reset)s | %(log_color)s%(message)s%(reset)s",
datefmt='%Y-%m-%d %H:%M:%S', # 自定义时间格式
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'bold_red',
}
)
# ... 后续步骤相同
输出效果:
2025-10-27 10:30:00 - DEBUG | This is a debug message.
2025-10-27 10:30:00 - INFO | This is an info message.
...
手动实现(无需第三方库,适合理解原理)
如果你不想安装第三方库,或者想了解其背后的原理,可以手动实现,这主要依赖于 ANSI 转义码。
ANSI 转义码是一套标准的控制码,可以控制终端的文本颜色、样式等。
定义颜色常量
定义一些常用的 ANSI 颜色代码。
# ANSI escape codes for colors RESET = "\033[0m" BLACK = "\033[30m" RED = "\033[31m" GREEN = "\033[32m" YELLOW = "\033[33m" BLUE = "\033[34m" MAGENTA = "\033[35m" CYAN = "\033[36m" WHITE = "\033[37m" BRIGHT_BLACK = "\033[90m" BRIGHT_RED = "\033[91m" BRIGHT_GREEN = "\033[92m" BRIGHT_YELLOW = "\033[93m" BRIGHT_BLUE = "\033[94m" BRIGHT_MAGENTA = "\033[95m" BRIGHT_CYAN = "\033[96m" BRIGHT_WHITE = "\033[97m"
创建自定义的 Formatter
我们需要创建一个继承自 logging.Formatter 的子类,并重写 format 方法,在格式化日志消息时插入颜色代码。
import logging
class ColoredFormatter(logging.Formatter):
"""A custom formatter that adds color to log output."""
# ANSI escape codes for colors
COLORS = {
logging.DEBUG: "\033[36m", # CYAN
logging.INFO: "\033[32m", # GREEN
logging.WARNING: "\033[33m", # YELLOW
logging.ERROR: "\033[31m", # RED
logging.CRITICAL: "\033[91m", # BRIGHT_RED
}
RESET = "\033[0m"
def format(self, record):
# Get the color for the log level
color = self.COLORS.get(record.levelno, self.RESET)
# Add the color to the log message
# We modify the record's message directly
record.msg = f"{color}{record.msg}{self.RESET}"
# Call the parent class's format method
return super().format(record)
# --- 使用这个自定义 Formatter ---
# 1. 创建 logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 2. 创建 handler
handler = logging.StreamHandler()
# 3. 创建我们的 ColoredFormatter
formatter = ColoredFormatter(
fmt="%(asctime)s - %(levelname)-8s - %(message)s",
datefmt='%Y-%m-%d %H:%M:%S'
)
handler.setFormatter(formatter)
# 4. 添加 handler 到 logger
logger.addHandler(handler)
# 5. 输出日志
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.")
原理说明:
- 我们创建了一个
ColoredFormatter类。 - 在
format方法中,我们获取日志记录的级别(record.levelno)。 - 根据级别,我们从
COLORS字典中找到对应的 ANSI 颜色代码。 - 我们将颜色代码、原始消息和重置代码拼接起来,赋值给
record.msg。 - 调用
super().format(record)来执行标准的日志格式化逻辑,但它处理的是已经被我们“上色”过的消息。
使用 Rich 库(功能最强大)
Rich 是一个功能极其强大的 Python 库,用于在终端中创建美观的输出,它内置了出色的日志处理功能,不仅能轻松实现颜色,还能支持表格、进度条、语法高亮等。
安装
pip install rich
使用 rich.logging 的 install()
Rich 提供了一个最简单的方式:rich.logging.install(),它会自动为你配置好一个带有颜色、时间、路径和文件名的 Handler。
import logging
from rich.logging import install
# 使用 rich.logging.install() 一键安装
# 它会返回一个 handler,你可以直接添加到 logger
# 你也可以不接收返回值,它会自动配置 root logger
handler = install()
logger = logging.getLogger(__name__)
# 设置日志级别
logger.setLevel(logging.DEBUG)
# 输出日志
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.")
输出效果(非常华丽):
2025-10-27 10:35:00 | __main__ | DEBUG | This is a debug message
2025-10-27 10:35:00 | __main__ | INFO | This is an info message
2025-10-27 10:35:00 | __main__ | WARNING | This is a warning message
2025-10-27 10:35:00 | __main__ | ERROR | This is an error message
2025-10-27 10:35:00 | __main__ | CRITICAL | This is a critical message
(Rich 会自动为不同级别应用不同的颜色,并且格式非常清晰)
高级自定义(使用 RichHandler)
如果你想进行更精细的控制,可以使用 RichHandler。
import logging
from rich.console import Console
from rich.logging import RichHandler
# 创建一个 RichHandler
# 你可以传入一个 Console 实例来控制输出目标
console = Console()
handler = RichHandler(console=console, show_time=True, show_path=True)
# 创建 logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(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.")
logger.critical("This is a critical message.")
总结与对比
| 方法 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
colorlog |
简单易用,专门为日志设计,配置灵活 | 需要安装第三方库 | 大多数项目,快速实现彩色日志的首选。 |
| 手动实现 | 无需依赖,能深入理解 logging 和 ANSI 码原理 |
代码量稍多,功能相对单一 | 学习、面试、或者对项目有极简依赖要求的环境。 |
Rich |
功能最强大,输出效果华丽,支持表格、进度条等 | 功能过于强大,对于只需要简单颜色的项目可能有点“杀鸡用牛刀” | 需要构建精美命令行界面(CLI)的应用,或者已经在使用 Rich 的项目。 |
推荐建议:
- 对于绝大多数 Python 开发者,直接使用
colorlog是最省心、最高效的选择。 - 如果你追求极致的简洁和零依赖,或者想深入理解底层原理,选择手动实现。
- 如果你的项目不仅需要日志,还需要在终端绘制复杂的界面,
Rich是不二之选。
