The project uses the logging Timedrotatingfilehandler:
#!/user/bin/env python#-*-coding:utf-8-*-import loggingfrom logging.handlers Import timedrotatingfilehandlerlog = log Ging.getlogger () file_name = "./test.log" Logformatter = logging. Formatter ('% (asctime) s [% (LevelName) s]|% ( Message) s ') LogHandle = Timedrotatingfilehandler (file_name, ' Midnight ', 1, 2) loghandle.setformatter (Logformatter) Loghandle.suffix = '%y%m%d ' Log.addhandler (loghandle) log.setlevel (logging. DEBUG) Log.debug ("Init successful")
Refer to the official documentation for Python logging:
Https://docs.python.org/2/library/logging.html
Look at the Getting started instance to see the use of time-rotated content:
Import logging# Create Loggerlogger = Logging.getlogger (' simple_example ') logger.setlevel (logging. DEBUG) # Create console handler and set level to DEBUGCH = logging. Streamhandler () Ch.setlevel (logging. DEBUG) # Create Formatterformatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s ') # Add Formatter to Chch.setformatter (Formatter) # Add CH t o Loggerlogger.addhandler (CH) # ' application ' codelogger.debug (' Debug message ')
Looking down, there is nothing wrong with the place.
Then look at the logging code, find the Timedrotatingfilehandler related content, which deletes the contents of the expired log:
logging/handlers.py
def getfilestodelete (self): "" " determine the files to delete when rolling over . More specific than the earlier method, which just used Glob.glob (). "" DirName, BaseName = Os.path.split (self.basefilename) fileNames = Os.listdir (dirName) result = [] prefix = BaseName + "." Plen = len (prefix) for fileName in fileNames: if filename[:p len] = = Prefix: suffix = filename[plen:] If Self.extMatch.match (suffix): result.append (Os.path.join (DirName, fileName)) result.sort () if Len (Result) < self.backupcount: result = [] else: result = Result[:len (result)-self.backupcount]< C19/>return result
The principle of rotation is to find the log directory, matching the suffix suffix of the file, added to the delete list, if the specified number is added to the list to be deleted, and then look at the principle of matching:
elif Self.when = = ' D ' or self.when = = ' Midnight ': self.interval = one day self.suffix = "%y-%m-%d " Self.extmatch = r" ^\d{4}-\d{2}-\d{2}$ "
Exmatch is a regular match, the format is-separated by the time, and we set ourselves a new suffix without-separating:
Loghandle.suffix = '%y%m%d '
This will not find the file you want to delete and will not delete the associated log.
Python Logging log rotation file does not remove the problem resolution method