继承或者调用
# coding=utf-8
import datetime
import logging
import ctypes
import os
import time
# Windows CMD命令行 字体颜色定义 text colors
FOREGROUND_BLACK = 0x00 # black.
FOREGROUND_DARKBLUE = 0x01 # dark blue.
FOREGROUND_DARKGREEN = 0x02 # dark green.
FOREGROUND_DARKSKYBLUE = 0x03 # dark skyblue.
FOREGROUND_DARKRED = 0x04 # dark red.
FOREGROUND_DARKPINK = 0x05 # dark pink.
FOREGROUND_DARKYELLOW = 0x06 # dark yellow.
FOREGROUND_DARKWHITE = 0x07 # dark white.
FOREGROUND_DARKGRAY = 0x08 # dark gray.
FOREGROUND_BLUE = 0x09 # blue.
FOREGROUND_GREEN = 0x0a # green.
FOREGROUND_SKYBLUE = 0x0b # skyblue.
FOREGROUND_RED = 0x0c # red.
FOREGROUND_PINK = 0x0d # pink.
FOREGROUND_YELLOW = 0x0e # yellow.
FOREGROUND_WHITE = 0x0f # white.
STD_OUTPUT_HANDLE = -11
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
log_path = os.path.dirname(os.path.dirname(__file__)).replace("/", "\\") + "\\Logs"
if not os.path.exists(log_path):
os.mkdir(log_path) # 如果不存在这个logs文件夹,就自动创建一个
log_name = os.path.join(log_path, '%s.log' % time.strftime('%Y-%m-%d')) # 文件的命名
def set_color(color, handle=std_out_handle):
result = ctypes.windll.kernel32.SetConsoleTextAttribute(handle, color)
return result
class Logs:
def __init__(self):
self.log_name = log_name
clevel = logging.DEBUG
Flevel = logging.DEBUG
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
fmt = logging.Formatter('[%(asctime)s][%(levelname)s] %(message)s')
# 设置CMD日志
sh = logging.StreamHandler()
sh.setFormatter(fmt)
sh.setLevel(clevel)
# 设置文件日志
fh = logging.FileHandler(self.log_name, encoding="utf-8")
fh.setFormatter(fmt)
fh.setLevel(Flevel)
self.logger.addHandler(sh)
self.logger.addHandler(fh)
self.handle_logs()
@staticmethod
def get_file_sorted(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
@staticmethod
def TimeStampToTime(timestamp):
"""格式化时间"""
timeStruct = time.localtime(timestamp)
return str(time.strftime('%Y-%m-%d', timeStruct))
@staticmethod
def delete_logs(file_path):
try:
os.remove(file_path)
except PermissionError as e:
Logs().warning('删除日志文件失败:{}'.format(e))
def handle_logs(self):
"""处理日志过期天数和文件数量"""
dir_list = ['Logs'] # 要删除文件的目录名
for file_dir in dir_list:
dirPath = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + '\\' + 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 debug(self, message, color=FOREGROUND_BLUE):
set_color(color)
self.logger.debug(message)
set_color(FOREGROUND_WHITE)
def info(self, message, color=FOREGROUND_GREEN):
set_color(color)
self.logger.info(message)
set_color(FOREGROUND_WHITE)
def warning(self, message, color=FOREGROUND_YELLOW):
set_color(color)
self.logger.warning(message)
set_color(FOREGROUND_WHITE)
def error(self, message, color=FOREGROUND_RED):
set_color(color)
self.logger.error(message)
set_color(FOREGROUND_WHITE)
def cri(self, message, color=FOREGROUND_DARKRED):
set_color(color)
self.logger.critical(message)
set_color(FOREGROUND_WHITE)
if __name__ == '__main__':
logyyx = Logs()
logyyx.debug('一个debug信息')
logyyx.info('一个info信息')
logyyx.warning('一个warning信息')
logyyx.error('一个error信息')
logyyx.cri('一个致命critical信息')