Python logging模块封装实现原理与四大组件解析
本文深入解析Python logging模块的封装原理,详细阐述日志器、处理器、过滤器和格式器四大核心组件的功能与协作机制。通过实际代码示例,展示如何配置日志路径、级别及输出格式,帮助开发者构建稳定高效的日志记录系统,适用于各类Python应用开发场景。
Python日志系统简介
简介
日志追踪是记录软件运行过程中关键事件的有效手段,开发者可通过调用日志接口来持久化保存这些运行时信息。
每个日志事件均包含一条可选的消息,该消息可附带额外的变量数据,以便更精确地描述发生的具体情况。
日志事件具备不同的严重性等级,用于区分信息的重要程度,便于后续的分类处理与筛选。
logging模块四大核心组件
Python的logging日志系统由四大核心组件构成,它们协同工作以完成日志的生成、过滤、格式化和输出。
- 日志器(Logger)
- 日志器(Logger)是应用程序代码直接调用的接口,负责接收日志请求并将其传递给相应的处理器。
- 处理器(Handler)
- 处理器(Handler)负责将日志记录发送到指定的目标位置,如文件、控制台或网络服务器。
- 过滤器(Filter)
- 过滤器(Filter)用于决定哪些日志记录应当被输出,其余不符合条件的记录将被忽略,从而实现精细的控制。
- 格式器(Formatter)
- 格式器(Formatter)控制日志输出的具体样式,包括时间戳、日志级别、消息内容等字段的排列方式。
日志封装代码实现
以下是基于上述原理实现的日志封装代码示例,展示了如何配置日志路径、级别及输出格式。
import os, time, logging, sys
from Common.plugs.get_config import r_config
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if sys.platform == "win32":
ENV_CONF_DIR = os.path.join(BASE_DIR, 'Common/conf/env_config.ini').replace('/', '\\')
else:
ENV_CONF_DIR = os.path.join(BASE_DIR, 'Common/conf/env_config.ini')
log_path = r_config(ENV_CONF_DIR, "log", "log_path")
class Log:
def __init__(self, log_path):
self.logName = os.path.join(log_path, '{0}.log'.format(time.strftime('%Y-%m-%d')))
def console_log(self, level, message):
# 创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# 创建一个handler,用于 debug 写入日志文件
debug_file = logging.FileHandler(self.logName, 'a+', encoding='utf-8')
debug_file.setLevel(logging.DEBUG)
# 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
debug_file.setFormatter(formatter)
ch.setFormatter(formatter)
# 给logger添加handler
logger.addHandler(debug_file)
logger.addHandler(ch)
# 记录一条日志
if level == 'info':
logger.info(message)
elif level == 'debug':
logger.debug(message)
elif level == 'warning':
logger.warning(message)
elif level == 'error':
logger.error(message)
elif level == 'critical':
logger.critical(message)
logger.removeHandler(ch)
logger.removeHandler(debug_file)
debug_file.close()
def debug(self, message): #最详细日志信息, 多用于问题诊断
self.console_log('debug', message)
def info(self, message): #仅次于DEBUG, 多用于记录关键点信息, 确保程序按预期执行
self.console_log('info', message)
def warning(self, message): #低等级故障, 但程序仍能运行, 如磁盘空间不足警告
self.console_log('warning', message)
def error(self, message): #由于比WARNING严重的问题, 导致某些功能不能正常运行时的记录
self.console_log('error', message)
def critical(self, message): 严重错误, 导致应用程序不能继续运行时的记录
self.console_log('critical', message)
if __name__ == '__main__':
Log(log_path).info("adasd")
Log(log_path).error("dsadasddasd")
'''
本文完整介绍了Python logging模块的封装实现原理,希望能为读者的技术学习提供有益参考,欢迎持续关注与支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













