python logging compression

9-22 1,603 views

https://stackoverflow.com/questions/8467978/python-want-logging-with-log-rotation-and-compression

import logging
import logging.handlers
import zipfile
import codecs
import sys
import os
import time
import glob

class TimedCompressedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
    """
    Extended version of TimedRotatingFileHandler that compress logs on rollover.
    """
    def doRollover(self):
        """
        do a rollover; in this case, a date/time stamp is appended to the filename
        when the rollover happens.  However, you want the file to be named for the
        start of the interval, not the current time.  If there is a backup count,
        then we have to get a list of matching filenames, sort them and remove
        the one with the oldest suffix.
        """

        self.stream.close()
        # get the time that this sequence started at and make it a TimeTuple
        t = self.rolloverAt - self.interval
        timeTuple = time.localtime(t)
        dfn = self.baseFilename + "." + time.strftime(self.suffix, timeTuple)
        if os.path.exists(dfn):
            os.remove(dfn)
        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])
        #print "%s -> %s" % (self.baseFilename, dfn)
        if self.encoding:
            self.stream = codecs.open(self.baseFilename, 'w', self.encoding)
        else:
            self.stream = open(self.baseFilename, 'w')
        self.rolloverAt = self.rolloverAt + self.interval
        if os.path.exists(dfn + ".zip"):
            os.remove(dfn + ".zip")
        file = zipfile.ZipFile(dfn + ".zip", "w")
        file.write(dfn, os.path.basename(dfn), zipfile.ZIP_DEFLATED)
        file.close()
        os.remove(dfn)

if __name__ == '__main__':
    if not os.path.exists( CurrentDir() + '/log' ):
        os.mkdir( CurrentDir() + '/log' )
    logfile = os.path.abspath( CurrentDir() + '/log/ftpserver.log' )

    logging.basicConfig(level=logging.DEBUG)
    thandler = TimedCompressedRotatingFileHandler(logfile, when="m", interval=1, backupCount=7)
    tformatter = logging.Formatter('%(asctime)s |%(levelname)1.1s| [%(thread)d] %(name)s:%(message)s')  
    thandler.setFormatter(tformatter)
    thandler.setLevel(logging.DEBUG)

    logger.addHandler(thandler)
    # logging.root.addHandler(thandler)

OpenCV-Python

OpenCV-Python OpenCV-Python Installing OpenCV from prebuilt binaries Below Python packages are to be downloaded and installed to their default lo...

阅读全文

Python 乱码解决

''.decode(sys.getfilesystemencoding())

阅读全文

python hideconsole

def hideConcole(): import ctypes kernel32 = ctypes.WinDLL('kernel32') user32 = ctypes.WinDLL('user32') SW_HIDE = 0 hWnd = k...

阅读全文

1 条评论

欢迎留言