700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Python实现打印日志到文件类(Logging)

Python实现打印日志到文件类(Logging)

时间:2023-01-12 04:06:19

相关推荐

Python实现打印日志到文件类(Logging)

背景:俗话说的好,『打印日志光荣,单步输出可耻』,想着实现个python的项目间可通用的日志打印类

环境:Python3.8,mac10.15.6

知识记录:Logging库使用方法简单来说就是提供了一个打印日志的载体(logger),而handler就是这个工具中的模块,具体打印日志是handler决定的(输出地点,格式等等),执行logger相当于执行里头所有的handler(互不干扰)。

功能:在文件当前存储目录下创建Logs文件夹,根据时间(精确到小时)生成日志文件

使用方法:在项目目录创建py文件,将代码copy过去,然后在项目中如果有需要打印日志的地方直接调用对应等级的方法就行。

效果图:

代码:

import loggingimport osimport timeclass Log:def __init__(self):self.logger = logging.getLogger() #创建loggerself.logger.setLevel(logging.INFO) #日志root等级self.log_path = os.path.dirname(os.path.realpath(__file__)) + '/Logs/' #日志目录#日志内容格式self.formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")if os.path.exists(self.log_path) == False: #目录不存在就创建os.makedirs(self.log_path)def printLog(self,log_type,log_content): #输出日志logTime = time.strftime('%Y%m%d%H', time.localtime(time.time())) #当前时间到小时log_file = self.log_path + logTime + '.log' #文件名if os.path.exists(log_file) == False: #日志文件不存在就创建fd = open(log_file, mode="w", encoding="utf-8")fd.close()handler = logging.FileHandler(log_file, mode='a')handler.setLevel(logging.DEBUG) # handler的日志等级handler.setFormatter(self.formatter) # 设置日志格式self.logger.addHandler(handler) #添加handlerif log_type == 0:self.logger.info(log_content)elif log_type == 1:self.logger.warning(log_content)elif log_type == 2:self.logger.error(log_content)else:self.logger.critical(log_content)self.logger.removeHandler(handler) #记得删除handler防止重复打印def printInfo(self,log_content):self.printLog(0,log_content)def printWarning(self,log_content):self.printLog(1,log_content)def printError(self,log_content):self.printLog(2,log_content)def printCritical(self,log_content):self.printLog(3,log_content)if __name__ == '__main__':Log = Log()Log.printInfo('不')Log.printWarning('点')Log.printError('赞')Log.printCritical('吗')Log.printWarning('( ´͈ ᵕ `͈ )◞♡')

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。