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模块内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关内容

热门资讯

从... 想写但不知道写什么?我终于找到了写书评或者拆开手稿的方法,但一个月内我无法完成这本书。我写了一篇书评...
命... 致谢VSRC 衷心感谢其行业合作伙伴 Bill Rice 贡献的高质量原创文章。 本文介绍本地命令行...
樊... 材料太多了,怕你忽略文/范家祥共 1001 字 | 建议阅读时间:2分钟作家白先勇曾经说过,一个作家...
提... 昨天科技之光转载的《》文章大家都看过了。 那你一定明白什么是GitHub了吧?这是开源和私有软件项目...
婚... 婚纱摄影的前期制作决定了婚纱摄影成品的丰富程度,婚纱摄影的后期制作决定了婚纱摄影成品的品质。 那么,...
西... 据2017年11月30日报道,硬盘作为计算机的主要存储介质之一,现在已经被人们广泛使用。 同时,硬盘...
美... “美图本身是一家处理图片的公司,但用户除了把图片发布在INS、Facebook、微博、朋友圈上,没有...
李... 李益民 杭州市第一人民医院护理部主任沉虹 杭州市第三人民医院皮肤一科主任王恒 杭州市疾病预防控制中心...
I... 今天,李之君为大家带来了三款IObit Win软件,高效卸载清理工具IObit Uninstalle...
整... 抖音的评论配音是怎么做的? 流行的短视频配音软件哪家最好? 今天小编给大家带来一款集多种功能于一体的...
私... “利用光和影为你创造梦想”每个女孩都期待着一场完美的婚礼,而一帧一帧的婚礼视频剪辑,正是新人一生中最...
,... 配音软件是一个非常实用的工具,可以让我们将文本转换为语音,可以用于各种场景,比如朗读文章、制作语音广...
不... 图片剪切工具的秘密! 如何剪出另一张照片? 这三个工具将帮助您事半功倍!在当今的社交媒体和数字时代手...
联... 一直关注连川公众号的朋友都知道,连川云平台已于2018年12月6日正式上线(:5390/index....
澳... 小宇说道:对于儿童玩具,我一直认为它们很贵,没有三位数是不可能买的。但这块磁力拼图拿在我手里就是一个...
磁... 本文由阿刚原创,首发于乐软博客()欢迎关注乐软博客微信公众号“阿刚同学”360作为国内安全防护公司,...
简... 当我们需要使用某种格式的图片,但是发现手头的图片是其他格式的,那么我们就需要对图片进行格式转换操作。...
修... 硬盘是触摸POS收银机非常重要的一部分。 所有信息和数据将自动存储在硬盘中。 一旦硬盘出现故障,有时...
电... 电影品质! 4款超棒的仙女拼图软件分享!用对软件,无用电影不删除,一举成大片! 分享4款益智软件!...
2... 以“工业互联网赋能千行百业,数字经济引领高质量发展”为主题的2023中国国际数字经济博览会将于9月6...