python自定义封装带颜色的logging模块
admin
2023-08-16 06:25:41
0

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 = encodingself.file = fileself.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"] != 0time.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"] != 0time.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"] != 0time.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"] != 0time.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: 打印日志信息
python自定义封装带颜色的logging模块
文章图片

避坑:不要用这种方式去调用日志等级方法 会出现日志打印定位路径错误 只能定位在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模块的文章就介绍到这了,更多相关python logging模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关内容

热门资讯

超... 本文目录导航: 超级云计算是什么 怎么做难看的PPT 1、...
谢... 本文目录导航: 请问云主机是什么 云主机有什么好处 具体的教程,谢谢! 云...
w... 本文目录导航: wps是什么意思 ppt的新配置designer和morp...
大... 本文目录导航: 大专学什么专业务工率高? 未来十年务工率最高的几大专业都是...
软... 本文目录导航: 软件技术专升本可以报什么专业 云计算专升本可以报医学吗 ...
云... 本文目录导航: 云计算务工前景 云计算务工方向及前景怎样样 ...
学... 本文目录导航: 学云计算进去无能嘛 云计算技术与运行是干什么的 ...
中... 本文目录导航: 如何了解云计算,中国的云计算产业开展现状如何 云计算未来几...
云... 本文目录导航: 云计算1+x证书含金量 云计算须要考什么证书 ...
云... 本文目录导航: 云计算股票龙头股票有哪些? 普通云计算概念龙头股有哪些?...
大... 本文目录导航: 大专云计算技术运行务工方向 大专毕业证上是物联网,实践学习...
大... 本文目录导航: 大数据云计算有必要升本吗 内蒙古大专云计算技术与运行专业升...
9... 本文目录导航: 99%学霸假期逆袭必看网站 99%学霸假期逆袭必看网站 ...
云... 本文目录导航: 云计算属于哪个专业 云计算属于什么专业 计...
计... 本文目录导航: 计算机二级MSOffice上机操作题及答案 想做一篇关于解...
A... 本文目录导航: AI能否会彻底扭转上流职业市场,如律师、会计师和医师? A...
人... 本文目录导航: 人工智能芯片产业链有哪些? 更多本行业钻研剖析详见前瞻产业...
人... 本文目录导航: 人工智能会带来哪些风险? 或许有一天,人工智能机器人将取代...
a... 本文目录导航: ai智能写作软件哪个好 ai智能写作软件有哪些?ai智能对...
自... 本文目录导航: 自考本科计算机专业难吗 自考计算机专业须要考哪些科目 ...