python中如何自定义封装带颜色的logging模块
发表于:2024-10-27 作者:千家信息网编辑
千家信息网最后更新 2024年10月27日,本文小编为大家详细介绍"python中如何自定义封装带颜色的logging模块",内容详细,步骤清晰,细节处理妥当,希望这篇"python中如何自定义封装带颜色的logging模块"文章能帮助大家解决
千家信息网最后更新 2024年10月27日python中如何自定义封装带颜色的logging模块
本文小编为大家详细介绍"python中如何自定义封装带颜色的logging模块",内容详细,步骤清晰,细节处理妥当,希望这篇"python中如何自定义封装带颜色的logging模块"文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
自己在搭建python接口自动化框架 分享一些内容过程中想自己封装一个logger方法 根据logging进行二次封装 代码如下
import loggingimport osimport timeimport colorlogfrom logging.handlers import RotatingFileHandler# 创建文件目录cur_path = os.path.dirname(os.path.realpath(__file__)) # log_path是存放日志的路径log_path = os.path.join(os.path.dirname(cur_path), 'logs')if not os.path.exists(log_path): os.mkdir(log_path) # 如果不存在这个logs文件夹,就自动创建一个# 修改log保存位置timestamp = time.strftime("%Y-%m-%d", time.localtime())logfile_name = '%s.log' % timestamplogfile_path = os.path.join(log_path, logfile_name)# 定义不同日志等级颜色log_colors_config = { 'DEBUG': 'bold_cyan', 'INFO': 'bold_green', 'WARNING': 'bold_yellow', 'ERROR': 'bold_red', 'CRITICAL': 'red',}class Logger(logging.Logger): def __init__(self, name, level='DEBUG', file=None, encoding='utf-8'): super().__init__(name) self.encoding = encoding self.file = file self.level = level # 针对所需要的日志信息 手动调整颜色 formatter = colorlog.ColoredFormatter( '%(log_color)s%(levelname)1.1s %(asctime)s %(reset)s| %(message_log_color)s%(levelname)-8s %(reset)s| %(' 'log_color)s[%(filename)s%(reset)s:%(log_color)s%(module)s%(reset)s:%(log_color)s%(funcName)s%(' 'reset)s:%(log_color)s%(''lineno)d] %(reset)s- %(white)s%(message)s', reset=True, log_colors=log_colors_config, secondary_log_colors={ 'message': { 'DEBUG': 'blue', 'INFO': 'blue', 'WARNING': 'blue', 'ERROR': 'red', 'CRITICAL': 'bold_red' } }, style='%' ) # 日志输出格式 # 创建一个FileHandler,用于写到本地 rotatingFileHandler = logging.handlers.RotatingFileHandler(filename=logfile_path, maxBytes=1024 * 1024 * 50, backupCount=5) rotatingFileHandler.setFormatter(formatter) rotatingFileHandler.setLevel(logging.DEBUG) self.addHandler(rotatingFileHandler) # 创建一个StreamHandler,用于输出到控制台 console = colorlog.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(formatter) self.addHandler(console) self.setLevel(logging.DEBUG)logger = Logger(name=logfile_path, file=logfile_path)
使用时我们只需要引入封装好的类就行 直观美丽大方~
# 引入封装好的logger模块from common.logger_handler import loggerdef physical_strength(self, abnormal): """兑换体力异常通用方法""" if self.attrs.__contains__('costType'): attrs_Type = { "costType": abnormal, "count": self.attrs["count"] } response_Type = r().response(self.send_uid, self.code, self.event, attrs_Type) # 使用时直接调用logger.info()就行 logger.info(f"physical_strength_{abnormal},response_Type:{response_Type}") assert response_Type["code"] != 0 time.sleep(2) attrs_count = { "costType": self.attrs["costType"], "count": abnormal } response_count = r().response(self.send_uid, self.code, self.event, attrs_count) logger.info(f"physical_strength_{abnormal},response_count:{response_count}") assert response_count["code"] != 0 time.sleep(2) attrs_all = { "costType": abnormal, "count": abnormal } response_all = r().response(self.send_uid, self.code, self.event, attrs_all) logger.info(f"physical_strength_{abnormal},response_all:{response_all}") assert response_all["code"] != 0 time.sleep(2) else: attrs_count = { "count": abnormal } response_count = r().response(self.send_uid, self.code, self.event, attrs_count) logger.info(f"physical_strength_{abnormal},response_count:{response_count}") assert response_count["code"] != 0 time.sleep(2)
效果:按照 日期/时间/日志等级/文件名称/类/方法名称/代码行数展示(这里可以自己手动调整formatter参数 如果感觉展示太长的话)
%(levelno)s: 打印日志级别的数值
%(levelname)s: 打印日志级别名称
%(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
%(filename)s: 打印当前执行程序名
%(funcName)s: 打印日志的当前函数
%(lineno)d: 打印日志的当前行号
%(asctime)s: 打印日志的时间
%(thread)d: 打印线程ID
%(threadName)s: 打印线程名称
%(process)d: 打印进程ID
%(message)s: 打印日志信息
避坑:不要用这种方式去调用日志等级方法 会出现日志打印定位路径错误 只能定位在log封装类当前方法下
def debug(self, message): self.__console('debug', message) def info(self, message): self.__console('info', message) def warning(self, message): self.__console('warning', message) def error(self, message): self.__console('error', message)
读到这里,这篇"python中如何自定义封装带颜色的logging模块"文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注行业资讯频道。
日志
封装
颜色
方法
模块
名称
内容
文件
文章
等级
路径
代码
信息
手动
时间
程序
级别
线程
定位
调整
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
科来网络安全分析
网络安全群口快板
为什么数据库备份要开归档
水电站网络安全演练方案
成都柠檬云网络技术有限
网络安全师范大学
计算机网络技术要用游戏本吗
报业网络安全等级保护指导意见
数据库联网使用吗
长沙软件开发相关编制
广东区块链与网络安全蓝皮书
软件开发专业考研有哪些学校
联想st258服务器管理口
数据库 to date
上海网络技术哪家强
幻塔哪个服务器更好
5g网络安全设置
千万级即时通讯服务器
黄石软件开发价格
国泰安数据库查资产负债表
消费升级大数据库
中奇互联网科技有限公司
京津冀网络安全应急演练
学校机房电脑未连接到服务器
连接到mysql服务器
政府单位安排网络安全比赛
阿兹夫定数据库锁库
王者服务器维护要到几点
综合网络技术咨询价格信息
网络安全教育班会的心得体会