# coding:utf-8
import logging
from logging.handlers import RotatingFileHandler # 按文件大小滚动备份
import colorlog # 控制台日志输入颜色
import time
import datetime
import os 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',
} class Log:
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() def get_file_sorted(self, file_path):
"""最后修改时间顺序升序排列 os.path.getmtime()->获取文件最后修改时间"""
dir_list = os.listdir(file_path)
if not dir_list:
return
else:
dir_list = sorted(dir_list, key=lambda x: os.path.getmtime(os.path.join(file_path, x)))
return dir_list def TimeStampToTime(self, timestamp):
"""格式化时间"""
timeStruct = time.localtime(timestamp)
return str(time.strftime('%Y-%m-%d', timeStruct)) def handle_logs(self):
"""处理日志过期天数和文件数量"""
dir_list = ['report'] # 要删除文件的目录名
for dir in dir_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 in file_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 in file_list:
file_path = os.path.join(dirPath, i)
print(file_path)
self.delete_logs(file_path) def delete_logs(self, file_path):
try:
os.remove(file_path)
except PermissionError 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() # 关闭打开的文件 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) if __name__ == "__main__":
log = Log()
log.debug("---测试开始----")
log.info("操作步骤")
log.warning("----测试结束----")
log.error("----测试错误----")
参考:logging- Python的记录工具

万能日志输出,可直接使用。

Python Logging模块 输出日志颜色、过期清理和日志滚动备份的更多相关文章

  1. Python logging模块无法正常输出日志

    废话少说,先上代码 File:logger.conf [formatters] keys=default [formatter_default] format=%(asctime)s - %(name ...

  2. python logging模块使用

    近来再弄一个小项目,已经到收尾阶段了.希望加入写log机制来增加程序出错后的判断分析.尝试使用了python logging模块. #-*- coding:utf-8 -*- import loggi ...

  3. 读懂掌握 Python logging 模块源码 (附带一些 example)

    搜了一下自己的 Blog 一直缺乏一篇 Python logging 模块的深度使用的文章.其实这个模块非常常用,也有非常多的滥用.所以看看源码来详细记录一篇属于 logging 模块的文章. 整个 ...

  4. (转)python logging模块

    python logging模块 原文:http://www.cnblogs.com/dahu-daqing/p/7040764.html 1 logging模块简介 logging模块是Python ...

  5. python logging—模块

    python logging模块 python logging提供了标准的日志接口,python logging日志分为5个等级: debug(), info(), warning(), error( ...

  6. 0x03 Python logging模块之Formatter格式

    目录 logging模块之Formatter格式 Formater对象 日志输出格式化字符串 LogRecoder对象 时间格式化字符串 logging模块之Formatter格式 在记录日志是,日志 ...

  7. 0x01 Python logging模块

    目录 Python logging 模块 前言 logging模块提供的特性 logging模块的设计过程 logger的继承 logger在逻辑上的继承结构 logging.basicConfig( ...

  8. python logging模块可能会令人困惑的地方

    python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...

  9. python logging模块+ 个人总结

    原文地址:http://www.cnblogs.com/sislcb/archive/2008/11/25/1340627.html 从Python2.3版本中开始引入的logging模块为应用提供了 ...

随机推荐

  1. TCP断线重连

    struct sockaddr_in TempSadd; TempSadd.sin_family = AF_INET; TempSadd.sin_port = htons(m_ServerPort); ...

  2. 树莓派mariadb 设置密码

    参考: sudo mysql -u root -p select Host,User,plugin from mysql.user where User='root'; plugin(加密方式)是un ...

  3. IT观察】网络通信、图片显示、数据库操作……Android程序员如何利用开源框架

    每个Android 程序员都不是Android应用开发之路上孤军奋战的一个人,GitHub上浩如烟海的开源框架或类库就是前人为我们发明的轮子,有的轮子能提高软件性能,而有的轮子似乎是以牺牲性能为代价换 ...

  4. Python类和实例方法和属性的动态绑定

    python中实例创建后可以给实例绑定任何属性和方法 class Student(object): pass 给实例绑定一个属性: s=Student() s.name='Michel' print ...

  5. MTK 关闭耳机调至最大音量时,提示损伤听力

    android开发之耳机调至最大音量时,提示损伤听力 android开发之耳机调至最大音量时,提示损伤听力 通过提示语,我们可以查出,只要的逻辑代码是在framework/base/packages/ ...

  6. 三维计算机视觉 —— 中层次视觉 —— RCNN Family

    RCNN是从图像中检测物体位置的方法,严格来讲不属于三维计算机视觉.但是这种方法却又非常非常重要,对三维物体的检测非常有启发,所以在这里做个总结. 1.RCNN - the original idea ...

  7. centos 安装python PIL模块

    转载:https://www.cnblogs.com/ccdc/p/4069112.html 1.安装 使用yum安装缺少类库: #尤其重要,否则会报错 yum install python-deve ...

  8. WINDOWS自带md5校验工具

    WINDOWS自带的工具certutil.exe,   certutil -hashfile chropp.exe MD5; 就可以了

  9. Linux提权:从入门到放弃

    *原创作者:piece of the past,本文属Freebuf原创奖励计划,未经许可禁止转载 日站就要日个彻底.往往我们能拿下服务器的web服务,却被更新地比西方记者还快的管理员把内网渗透的种子 ...

  10. 2 虚拟机Oracle11.2.0.4服务器端,第三方图形化界面安装步骤

    环境: 虚拟机:winserver 2012r2  数据中心版   64位 物理主机:win7 旗舰版 64位 网络环境:网线连接内网,WiFi外网 一.虚拟机相关设置 包括计算机名,与物理主机的网络 ...