#!/usr/bin/python # -*- coding: GBK -*- # ##@package # # @todo: # # @author: Alee # @date 2018-7-18 ÉÏÎç11:40:53 # @version 1.0 # # @note: # #--------------------------------------------------------------------- #¸ù¾Ýʱ¼äÇл»Ä¿Â¼ºÍÎļþµÄÎļþ´¦ÀíÆ÷ from logging.handlers import * class TimeRotatingPathFileHandler(TimedRotatingFileHandler): def __init__(self, root, filename, when = 'h', interval = 1, backupCount = 0, encoding = None, delay = False, utc = False): #´´½¨Êä³öĿ¼Êý t = int(time.time()) if utc: timeTup = time.gmtime(t) else: timeTup = time.localtime(t) year = timeTup[0] month = timeTup[1] day = timeTup[2] self.root = root self.filename = filename self.baseFilename = self.getBaseFileName(self.root, year, month, day, self.filename) #print 'baseFileName = %s'%self.baseFilename filepath = os.path.dirname(self.baseFilename) self.ensurePath(filepath) #¸Ä±äµ±Ç°¹¤×÷Ŀ¼ #if not (os.getcwd() == filepath): # os.chdir(filepath) TimedRotatingFileHandler.__init__(self, self.baseFilename, when, interval, backupCount, encoding, delay, utc) #self.suffix = ''#²»Ö¸¶¨ºó׺ def getBaseFileName(self, root, year, month, day, filename): filenameWithoutExt = filename.split('.')[0] return os.path.join(root, '%04d-%02d\\%s\\%02d\\%s'%(year, month, filenameWithoutExt, day, filename)) def ensurePath(self, filepath): if not os.path.exists(filepath): os.makedirs(filepath) def doRollover(self): lastRolloverTime = self.rolloverAt #TimedRotatingFileHandler.doRollover(self) if self.stream: self.stream.close() self.stream = None #»ñÈ¡ÉÏÒ»´ÎÇл»µÄʱ¼ä t = self.rolloverAt - self.interval if self.utc: timeTuple = time.gmtime(t) else: timeTuple = time.localtime(t) filenameTuple = self.filename.split('.') filename = '' if len(filenameTuple) == 1: filename = '%s-%s'%(filenameTuple[0], time.strftime(self.suffix, timeTuple)) else: filename = '%s-%s.%s'%(filenameTuple[0], time.strftime(self.suffix, timeTuple), filenameTuple[len(filenameTuple) - 1]) dfn = os.path.join(self.root, '%04d-%02d\\%s\\%02d\\%s'%(timeTuple[0], timeTuple[1], filenameTuple[0], timeTuple[2], filename)) #dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple) if os.path.exists(dfn): os.remove(dfn) # print 'dfn = %s baseFilename = %s'%(dfn, self.baseFilename) #¿ÉÄÜÓÉÓÚ¸Äϵͳʱ¼ä»òÆäËûÈËΪԭÒòÔì³ÉÎļþÕÒ²»µ½ if os.path.exists(self.baseFilename): os.rename(self.baseFilename, dfn) if self.backupCount > 0: # find the oldest log file and delete it #s = glob.glob(self.baseFilename + ".20*") #if len(s) > self.backupCount: # s.sort() # os.remove(s[0]) for s in self.getFilesToDelete(): os.remove(s) currentTime = int(time.time()) newRolloverAt = self.computeRollover(currentTime) while newRolloverAt <= currentTime: newRolloverAt = newRolloverAt + self.interval #If DST changes and midnight or weekly rollover, adjust for this. if (self.when == 'MIDNIGHT' or self.when.startswith('W')) and not self.utc: dstNow = time.localtime(currentTime)[-1] dstAtRollover = time.localtime(newRolloverAt)[-1] if dstNow != dstAtRollover: if not dstNow: # DST kicks in before next rollover, so we need to deduct an hour newRolloverAt = newRolloverAt - 3600 else: # DST bows out before next rollover, so we need to add an hour newRolloverAt = newRolloverAt + 3600 self.rolloverAt = newRolloverAt #ÅжÏÊÇ·ñÐèÒªÇл»Îļþ¼Ð nextRolloverTime = self.rolloverAt if self.utc: lastRolloverTimeTup = time.gmtime(lastRolloverTime) nextRolloverTimeTup = time.gmtime(nextRolloverTime) else: lastRolloverTimeTup = time.localtime(lastRolloverTime) nextRolloverTimeTup = time.localtime(nextRolloverTime) lastRolloverYear = lastRolloverTimeTup[0] lastRolloverMonth = lastRolloverTimeTup[1] lastRolloverDay = lastRolloverTimeTup[2] nextRolloverYear = nextRolloverTimeTup[0] nextRolloverMonth = nextRolloverTimeTup[1] nextRolloverDay = nextRolloverTimeTup[2] if lastRolloverYear != nextRolloverYear or lastRolloverMonth != nextRolloverMonth or lastRolloverDay != nextRolloverDay: #Äê»òÔ¸ı䣬¸ü»»Îļþ¼Ð self.baseFilename = self.getBaseFileName(self.root, nextRolloverYear, nextRolloverMonth, nextRolloverDay, self.filename) # print 'need to rollove path:%s-%s -> %s-%s'%(lastRolloverYear, lastRolloverMonth, # nextRolloverYear, nextRolloverMonth) filepath = os.path.dirname(self.baseFilename) self.ensurePath(filepath) else: pass self.mode = 'w' self.stream = self._open() def test(): import logging mylogger = logging.getLogger('test') mylogger.setLevel(logging.DEBUG) hdlr = TimeRotatingPathFileHandler('d:\\ServerLog\\', 'AD.txt') fs = '%(asctime)s\t%(levelname)-8s\t%(message)s' dfs = '%Y-%m-%dT%H:%M:%S' fmt = logging.Formatter(fs, dfs) hdlr.setLevel(logging.DEBUG) hdlr.setFormatter(fmt) mylogger.addHandler(hdlr) # mylogger.info('test') # os.system('pause') exit = False cnt = 0 lastTime = time.time() while not exit: curTime = time.time() if curTime - lastTime >= 60: lastTime = curTime mylogger.info('test') if __name__ == "__main__": test()