Python Logging log rotation file does not delete the issue

Source: Internet
Author: User
Tags glob

Objective

Recently in the Python Project code that maintains the project, the project uses the Python log module logging, which sets the number of saved logs, but does not take effect, and cleans up the data periodically through contab.

Analysis

The project uses the logging Timedrotatingfilehandler:

1 #!/user/bin/env python2 #-*-coding:utf-8-*-3 4 ImportLogging5  fromLogging.handlersImportTimedrotatingfilehandler6Log =Logging.getlogger ()7file_name ="./test.log"8Logformatter = logging. Formatter ('% (asctime) s [% (LevelName) s]|% ( Message) s')9LogHandle = Timedrotatingfilehandler (file_name,'Midnight', 1, 2)Ten Loghandle.setformatter (logformatter) OneLoghandle.suffix ='%y%m%d' A Log.addhandler (LogHandle) - Log.setlevel (logging. DEBUG) -  theLog.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:

1 ImportLogging2 3 #Create Logger4Logger = Logging.getlogger ('Simple_example')5 Logger.setlevel (logging. DEBUG)6 7 #Create console handler and set level to debug8CH =logging. Streamhandler ()9 Ch.setlevel (logging. DEBUG)Ten  One #Create Formatter AFormatter = logging. Formatter ('% (asctime) s-% (name) s-% (levelname) s-% (message) s') -  - #Add formatter to CH the Ch.setformatter (Formatter) -  - #Add ch to logger - logger.addhandler (CH) +  - #' Application ' code +Logger.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

    defGetfilestodelete (self):"""determine the files to delete is 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) forFileNameinchFileNames:iffilename[:p len] = =Prefix:suffix=Filename[plen:]ifself.extMatch.match (suffix): result.append (Os.path.join (DirName, FileName)) Result.sort () ifLen (Result) <Self.backupCount:result= []        Else: Result= Result[:len (Result)-Self.backupcount]returnResult

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 ' D ' or ' Midnight ' :             # One day             " %y-%m-%d " = 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.

Summarize

1. The encapsulated library, try to use the Open interface, do not arbitrarily modify the internal variables;

2. There is a problem with the code, you can not find the reason, you may look at the code.

Python Logging log rotation file does not delete the issue

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.