自己定义一个python的logging类模块,方便其他程序调用
2021/6/19 9:56:50
本文主要是介绍自己定义一个python的logging类模块,方便其他程序调用,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
写于此,方便自己日后查找,直接复制到其他程序中使用
import time import os import colorlog import logging class MyLogging(): log_colors_config = { 'DEBUG': 'white', # cyan white 'INFO': 'green', 'WARNING': 'yellow', 'ERROR': 'red', 'CRITICAL': 'bold_red', } def __init__(self,filename=None,timeInName=False,con_level='warning',file_level='debug'): if not os.path.exists('./Logs'): os.makedirs('./Logs') if filename==None: filename = './Logs/' + time.strftime('%Y-%m-%d %H_%M_%S',time.localtime(time.time())) + '.log' else: if timeInName: filename = './Logs/' + time.strftime('%Y-%m-%d %H_%M_%S',time.localtime(time.time())) + '-' + filename + '.log' else: filename = './Logs/' + filename + '.log' self.logger = logging.getLogger('my_log') self.logger.setLevel(logging.DEBUG) #处理器Hander consoleHander = logging.StreamHandler() consoleHander.setLevel(self.get_level(con_level)) #不指定输出级别则采用logger的级别,都设置了则取最低级 fileHander = logging.FileHandler(filename=filename) fileHander.setLevel(self.get_level(file_level)) #formatter格式 formatter1 = logging.Formatter("%(asctime)s | %(levelname)s | %(filename)s - %(funcName)s : %(lineno)s | %(message)s") formatter2 = colorlog.ColoredFormatter(fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s', log_colors=self.log_colors_config) #给处理器设置格式 consoleHander.setFormatter(formatter2) fileHander.setFormatter(formatter1) #记录器设置处理器 self.logger.addHandler(consoleHander) self.logger.addHandler(fileHander) def get_level(self,level): dict = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'ctirical': logging.CRITICAL } return dict.get(level) def debug(self, msg): self.logger.debug(msg) def info(self, msg): self.logger.info(msg) def warning(self, msg): self.logger.warning(msg) def error(self, msg): self.logger.error(msg) def critical(self, msg): self.logger.critical(msg)
// An highlighted block if __name__ == '__main__': log1 = MyLogging('test',timeInName=True,con_level='debug') log1.debug('this is debug') log1.logger.info('this is info') log1.logger.warning('this is warning') log1.logger.error('This is error')
这篇关于自己定义一个python的logging类模块,方便其他程序调用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-25Python编程基础:变量与类型
- 2024-11-25Python编程基础与实践
- 2024-11-24Python编程基础详解
- 2024-11-21Python编程基础教程
- 2024-11-20Python编程基础与实践
- 2024-11-20Python编程基础与高级应用
- 2024-11-19Python 基础编程教程
- 2024-11-19Python基础入门教程
- 2024-11-17在FastAPI项目中添加一个生产级别的数据库——本地环境搭建指南
- 2024-11-16`PyMuPDF4LLM`:提取PDF数据的神器