python日志模块备份_Python Logging模块 输出日志颜色、过期清理和日志滚动备份
#coding:utf-8
importloggingfrom logging.handlers importRotatingFileHandler # 按文件大小滚动备份import colorlog #控制台日志输入颜色
importtimeimportdatetimeimportos
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文件夹,就自动创建一个
logName = os.path.join(log_path, '%s.log' % time.strftime('%Y-%m-%d')) #文件的命名
log_colors_config={'DEBUG': 'cyan','INFO': 'green','WARNING': 'yellow','ERROR': 'red','CRITICAL': 'red',
}classLog:def __init__(self, logName=logName):
self.logName=logName
self.logger=logging.getLogger()
self.logger.setLevel(logging.DEBUG)
self.formatter=colorlog.ColoredFormatter('%(log_color)s[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s',
log_colors=log_colors_config) #日志输出格式
self.handle_logs()defget_file_sorted(self, file_path):"""最后修改时间顺序升序排列 os.path.getmtime()->获取文件最后修改时间"""dir_list=os.listdir(file_path)if notdir_list:return
else:
dir_list= sorted(dir_list, key=lambdax: os.path.getmtime(os.path.join(file_path, x)))returndir_listdefTimeStampToTime(self, timestamp):"""格式化时间"""timeStruct=time.localtime(timestamp)return str(time.strftime('%Y-%m-%d', timeStruct))defhandle_logs(self):"""处理日志过期天数和文件数量"""dir_list= ['report'] #要删除文件的目录名
for dir indir_list:
dirPath= os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + '\\' + dir #拼接删除目录完整路径
file_list = self.get_file_sorted(dirPath) #返回按修改时间排序的文件list
if file_list: #目录下没有日志文件
for i infile_list:
file_path= os.path.join(dirPath, i) #拼接文件的完整路径
t_list = self.TimeStampToTime(os.path.getctime(file_path)).split('-')
now_list= self.TimeStampToTime(time.time()).split('-')
t= datetime.datetime(int(t_list[0]), int(t_list[1]),
int(t_list[2])) #将时间转换成datetime.datetime 类型
now = datetime.datetime(int(now_list[0]), int(now_list[1]), int(now_list[2]))if (now - t).days > 6: #创建时间大于6天的文件删除
self.delete_logs(file_path)if len(file_list) > 4: #限制目录下记录文件数量
file_list = file_list[0:-4]for i infile_list:
file_path=os.path.join(dirPath, i)print(file_path)
self.delete_logs(file_path)defdelete_logs(self, file_path):try:
os.remove(file_path)exceptPermissionError as e:
Log().warning('删除日志文件失败:{}'.format(e))def __console(self, level, message):#创建一个FileHandler,用于写到本地
fh = RotatingFileHandler(filename=self.logName, mode='a', maxBytes=1024 * 1024 * 5, backupCount=5,
encoding='utf-8') #使用RotatingFileHandler类,滚动备份日志
fh.setLevel(logging.DEBUG)
fh.setFormatter(self.formatter)
self.logger.addHandler(fh)#创建一个StreamHandler,用于输出到控制台
ch =colorlog.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(self.formatter)
self.logger.addHandler(ch)if level == 'info':
self.logger.info(message)elif level == 'debug':
self.logger.debug(message)elif level == 'warning':
self.logger.warning(message)elif level == 'error':
self.logger.error(message)#这两行代码是为了避免日志输出重复问题
self.logger.removeHandler(ch)
self.logger.removeHandler(fh)
fh.close()#关闭打开的文件
defdebug(self, message):
self.__console('debug', message)definfo(self, message):
self.__console('info', message)defwarning(self, message):
self.__console('warning', message)deferror(self, message):
self.__console('error', message)if __name__ == "__main__":
log=Log()
log.debug("---测试开始----")
log.info("操作步骤")
log.warning("----测试结束----")
log.error("----测试错误----")
python日志模块备份_Python Logging模块 输出日志颜色、过期清理和日志滚动备份相关推荐
- python logging模块使用_python logging模块使用
近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- importloggin ...
- python logging模块 默认_python logging模块
函数式简单配置 importlogging logging.debug('debug message') #计算或者工作的细节 logging.info('info message') #记录一些用户 ...
- python logging模块的作用及应用场景_Python logging模块原理解析及应用
一.logging日志模块等级 常见log级别从高到低: CRITICAL >ERROR >WARNING >INFO >DEBUG,默认等级为WARNING,即>=WA ...
- python logging 控制其他模块等级_Python常用模块:logging模块介绍
简单使用 #!/usr/local/bin/python# -*- coding:utf-8 -*-import logginglogging.debug('debug message')loggin ...
- python logging模块详解_python logging模块使用总结
目录 logging模块 日志级别 CRITICAL 50 ERROR 40 WARNING 30 INFO 20 DEBUG 10 logging.basicConfig()函数中的具体参数含义 f ...
- Python标准库中的logging模块
1.将日志输出到屏幕 import logging logging.debug('This is debug message') logging.info('This is ...
- python如何创建模块教程_Python创建模块及模块导入的方法
本文实例讲述了Python创建模块及模块导入的方法.分享给大家供大家参考.具体分析如下: python学习手册中写道: 定义模块,只要使用文本编辑器,把一些python代码输入到文本中,然后以.py为 ...
- python 多进程 调用模块内函数_python子进程模块subprocess详解与应用实例 之一
分类: Python/Ruby 2014-09-09 10:59:42 subprocess--子进程管理器 一.subprocess 模块简介 subprocess最早是在2.4版本中引入的. su ...
- python引入模块教程_python导入模块--案例
1 导入模块 1.1 问题 本案例要求先编写一个star模块,主要要求如下: 建立工作目录 ~/bin/ 创建模块文件 ~/bin/star.py 模块中创建pstar函数,实现打印50个星号的功能 ...
最新文章
- 一些有趣的题目(java)持续更新
- abap BDC 使用方法
- 今晚直播 | 商汤科技X-Lab刘宇:神经网络结构与大规模优化方法
- mysql rowdatapacket_arrays – 将此RowDataPacket对象数组缩小为单个对象
- 了解※数据科学※(一)之数据的概念及一个数据科学项目的流程分析
- java基础知识点_JAVA基础知识
- ipython怎么安装_ipython的两种安装方式
- mysql5.7卸载语句_MySQL5.7完全卸载
- 用MATLAB玩转机器人--第六章 用MATLAB玩转单关节机器人
- Redis常问面试题及答案
- 阿里 AI「一对多」挑战人类律师;谷歌或将推出自研手机和电脑芯片;JavaScript诞生25周年|极客头条...
- 最大子数组累加和(2种方法)
- Python字符的转义
- Faster rcnn相关文章研究
- angular : direative :comunication 指令之间的通讯
- 各种门锁的内部结构图_有没有这种执手门锁的内部结构图?
- 335x内核ddr3频率与电压修改
- 【181018】纯C 编写的太空大战打字游戏
- 成绩在C语言中怎么表示,c语言指数函数-分数在C语言中怎么表示分数和指数形式在C语 – 手机爱问...
- 10道虐心的Java面试题,被面试官虐哭了,同事一题都没答对
热门文章
- phpStorm重构快捷键(mac系统、持续更新)
- python初中必背语法_一些python语法的合集
- h5页 点击返回时关闭_在微信、支付宝、百度钱包实现点击返回按钮关闭当前页面和窗口...
- 度量相似性数学建模_一种基于粒子群位置更新思想灰狼优化算法的K-Means文本分类方法与流程...
- 无线连接 服务器,服务器无线远程连接
- oracle rds 运维服务_从运维的角度分析使用阿里云数据库RDS的必要性–你不应该在阿里云上使用自建的MySQL/SQL Server/Oracle/PostgreSQL数据库...
- C++中static关键字作用总结
- 一个服务器多个网站多个域名,多个域名一个服务器吗
- mongodb java报授权,mongoDB 3.0用户创建与授权
- memory拷贝与string拷贝的区别