# -*- coding: utf-8 -*-
__author__ = 'Secret608'
import logging import time import os import re class Log(object): def __init__(self, loggerName): ''' 进行日志初始化,包括存储路径、名称、级别、调用文件等 '''
#基本属性
self.logger = logging.getLogger(loggerName) self.logger.setLevel(logging.WARNING) #特有属性(文件地址+日志记录格式)
rq = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time())) log_path = os.path.join(os.path.dirname(os.getcwd()), 'logs') log_title = os.path.join(log_path, loggerName + '_'+ rq) + ".log" formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') log = logging.FileHandler(log_title) log.setFormatter(formatter) #加到基本属性中,得到一个完整的初始化对象
self.logger.addHandler(log) def getLog(self): return self.logger def delLog(self, fileName): log_path = os.path.join(os.path.dirname(os.getcwd()), 'logs') regexp = re.compile('^'+fileName+'s.*') filelist = os.listdir(log_path) try: [os.remove(os.path.join(log_path, i)) for i in filelist if regexp.match(i) == None] except WindowsError: pass
else: return "ok"
if __name__ == "__main__": a = Log("hah") a.delLog("hah")