python中的压缩(存档)旧日志文件

时间:2011-08-10 11:49:12

标签: python logging archive

我在Python中使用标准记录器库。例如,RotatingFileHandler可以每天旋转日志文件。

但它只是重命名它们。将是伟大的,如果它不仅可以重命名,而且还将旧文件放在zip(或gz,bzip等)存档中。

有没有简单的方法来实现这一目标?

3 个答案:

答案 0 :(得分:7)

我认为您最好的选择是延长RotatingFileHandler这样的事情(未经测试):

import os
from logging.handlers import RotatingFileHandler


COMPRESSION_SUPPORTED = {}

try:
   import gzip
   COMPRESSION_SUPPORTED['gz'] = gzip
except ImportError:
   pass

try:
   import zipfile
   COMPRESSION_SUPPORTED['zip'] = zipfile
except ImportError:
   pass


class NewRotatingFileHandler(RotatingFileHandler):

     def __init__(self, *args, **kws):
         compress_mode = kws.pop('compress_mode')

         try:
             self.compress_cls = COMPRESSION_SUPPORTED[compress_mode]
         except KeyError:
             raise ValueError('"%s" compression method not supported.' % compress_mode)

         super(NewRotatingFileHandler, self).__init__(self, *args, **kws)

     def doRollover(self):
         super(NewRotatingFileHandler, self).doRollover()

         # Compress the old log.
         old_log = self.baseFilename + ".1"
         with open(old_log) as log:
             with self.compress_cls.open(old_log + '.gz', 'wb') as comp_log:
                 comp_log.writelines(log)

         os.remove(old_log)

答案 1 :(得分:5)

接受的答案只会归档1个文件 - (basefile.log.1)。其他文件不归档。 此代码将归档除基本文件以外的所有日志文件。

private void googlePlusLogout() {
        if (mGoogleApiClient != null)
            if (mGoogleApiClient.isConnected()) {
                Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                mGoogleApiClient.disconnect();
                mGoogleApiClient.connect();
            }
    }

答案 2 :(得分:3)

您可以使用RotatingFileHandler初始化encoding='bz2-codec'来自动编写bz2压缩日志文件:

import logging
import logging.handlers as handlers

if __name__=='__main__':
    log_filename='log_rotate.bz2'
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.DEBUG)
    handler = handlers.RotatingFileHandler(
        log_filename, maxBytes=20, backupCount=5, encoding='bz2-codec')
    logger.addHandler(handler)
    for i in range(20):
        logger.debug('i = %d' % i)

PS。来自有效编码集的Python3 removed 'bz2-codec',因此该解决方案特定于Python2。