前言:
Python的logging模块是内建的、功能强大的日志系统,可通过简单的配置,就能满足基本到复杂的日志管理需求。它可以让你以各种方式记录错误、调试信息、以及其他运行时的信息,这些都是应用程序健壯性、可维护性的关键。
1 基础概念
在深入了解之前,先理解logging模块的几个基本概念:
Logger:应用程序代码直接使用的接口。
Handler:用于将日志记录(log record)发送到合适的目的地。
Formatter:用于配置日志信息的最终顺序、结构和内容。
Level:日志级别,如DEBUG、INFO、WARNING、ERROR、CRITICAL等,用于区分日志的重要性。
debug: 用于开发者调试,显示变量等详细信息; 正常版本不应包含
info: 通知用户关键的正常行为,如“主库添加成功”;用简单、明确的语言记录
warning:不正常或偏离预期的行为; 不会立即影响系统,但具有潜在风险
critical:未知的不正常行为,超出已知容错;可能会影响程序未来运行
error: 无法修复的严重错误;必须立即处理并可能需要停止程序。
1.1 简单的示例:
#!/usr/bin/env python
# coding=utf-8
"""
# @Time : 2024/4/8
# @Author : Summer
# @File : logger.py
# @describe:
"""
import logging
# 配置日志等级为INFO,日志格式等
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 获取logger对象
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.')
logger.critical('This is a critical message.')
对于简单的脚本或小型项目,basicConfig方法的配置足够使用。但是,对于更复杂的日志需求,可能需要配置多个handler、formatter,并灵活地应用不同的日志级别。
2 彩色日志
logging模块默认不支持彩色日志。要实现彩色日志,可以自定义Formatter,在输出的文本中加入终端色彩代码。一个简单的方式是使用colorlog包,它是一个允许彩色配置输出的第三方库。
colorlog的使用
#!/usr/bin/env python
# coding=utf-8
"""
# @Time : 2024/4/8
# @Author : Summer
# @File : logger.py
# @describe:
"""
import colorlog
import logging
# 创建logger对象
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# 创建handler
ch = logging.StreamHandler()
# 创建带颜色的formatter
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='%'
)
# 设置handler的formatter
ch.setFormatter(formatter)
# 将handler添加到logger中
logger.addHandler(ch)
# 记录示例日志
logger.debug('Debug message')
logger.info('Info message')
logger.warning('Warning message')
logger.error('Error message')
logger.critical('Critical message')
在这里,ColoredFormatter允许指定日志级别的颜色,改善日志的可读性。上述例子在日志级别、消息文本周围加入了颜色。
这只是logging模块以及如何实现彩色日志输出的一个简介。根据不同的日志策略和复杂性,logging模块提供的灵活性和功能可以大大帮助提升应用程序的质量和可维护性。
3 完整代码
下面给大家提供一个完整的封装,希望对大家有用
#!/usr/bin/env python
# coding=utf-8
"""
# @Time : 2024/4/8
# @Author : Summer
# @File : logger.py
# @describe:
"""
import logging
import os
import time
# ANSI escape codes for colors in terminal
class TerminalColor:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RESET = '\033[0m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
class ColorFormatter(logging.Formatter):
COLORS = {
logging.DEBUG: TerminalColor.CYAN,
logging.INFO: TerminalColor.GREEN,
logging.WARNING: TerminalColor.YELLOW,
logging.ERROR: TerminalColor.RED,
logging.CRITICAL: TerminalColor.RED + TerminalColor.WHITE
}
def format(self, record):
level_color = self.COLORS.get(record.levelno)
reset_color = TerminalColor.RESET
message = super(ColorFormatter, self).format(record)
return level_color + message + reset_color
log_path = os.path.join(os.path.dirname(__file__), 'logs')
if not os.path.exists(log_path):
os.mkdir(log_path)
class Log(object):
def __init__(self, log_name):
self.log_name = log_name
self.logname = os.path.join(log_path, '%s_%s.log' % (self.log_name, time.strftime('%Y_%m_%d')))
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
formatter = ColorFormatter('[%(asctime)s] - %(filename)s] - %(levelname)s: %(message)s')
# Create file handler
fh = logging.FileHandler(self.logname, 'a', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
# Create console handler with color support
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
self.logger.addHandler(fh)
self.logger.addHandler(ch)
def debug(self, message):
self.logger.debug(message)
def info(self, message):
self.logger.info(message)
def warning(self, message):
self.logger.warning(message)
def error(self, message):
self.logger.error(message)
def critical(self, message):
self.logger.critical(message)
if __name__ == "__main__":
log = Log('Confluence')
log.info("---测试开始----")
log.info("操作步骤1,2,3")
log.warning("----测试结束----")
log.error("----测试中有错误----")
log.critical("----测试中有致命错误----")
注意:日志颜色通常只在兼容ANSI颜色代码的终端内生效,而在日志文件中是不可见的。此外,某些操作系统或终端可能不支持或默认关闭了颜色输出,这就需要相应地配置环境或更换支持颜色的终端。