Apacheログローテートスクリプト

Apacheのログローテートスクリプト書いてみた。

#!/usr/bin/env python
# coding: utf-8
 
import os
import re
import glob
import datetime
import shutil
from subprocess import call
 
class logApache(object):
    def __init__(self, dirs=[], rlog='*_log', dlog='*_log.*', interval=90):
        self.__dirs = dirs
        self.__rlog = rlog
        self.__dlog = dlog
        self.__interval = interval
 
    def check_instance(self):
        for dir in self.__dirs:
            if not os.path.isdir(dir):
                raise Exception('Directory not found. {0}'.format(dir))
 
    def logrotate(self):
        self.check_instance()
        d = datetime.datetime.now()
        dtime = d.strftime('%Y%m%d')
        for dir in self.__dirs:
            for log in glob.iglob(os.path.join(dir, self.__rlog)):
                rename = ('.'.join([log, dtime]))
                if os.path.exists(rename):
                    continue
                shutil.move(log, rename)
                with open(log, 'w') as fp:
                    pass
 
    def graceful(self):
        cmd = '/usr/local/apache/bin/apachectl graceful'
        rtn = call(cmd, shell=True)
        if rtn:
            raise Exception('Failed to Apache graceful.')
 
    def logdelete(self):
        self.check_instance()
        rdate = re.compile(r'.*_log\.(.*)$')
        d = datetime.datetime.now()
        dtime = (d - datetime.timedelta(days=self.__interval)).strftime('%Y%m%d')
        for dir in self.__dirs:
            for log in glob.iglob(os.path.join(dir, self.__dlog)):
                if int(rdate.sub(r'\1', log)) < int(dtime):
                    os.unlink(log)
 
    @property
    def dirs(self):
        return self.__dirs
 
    @dirs.setter
    def dirs(self, value):
        if not isinstance(value, list):
            raise Exception('itgwApache.dirs should be specified in the list.')
        self.__dirs = value
 
    @property
    def rlog(self):
        return self.__rlog
 
    @rlog.setter
    def rlog(self, value):
        self.__rlog = value
 
    @property
    def dlog(self):
        return self.__dlog
 
    @dlog.setter
    def dlog(self, value):
        self.__dlog = value
 
    @property
    def interval(self):
        return self.__interval
 
    @interval.setter
    def interval(self, value):
        r = re.compile(r'[^0-9]')
        if r.search(value):
            raise Exception('itgwApache.interval should be specified in the integer.')
        self.__interval = value
 
if __name__ == '__main__':
    BASE_DIR = '/usr/local/apache'
    LOG_DIR = [ os.path.join(BASE_DIR, 'logs') ]
    LOG_DIR.extend(glob.glob(os.path.join(BASE_DIR, 'vhosts', '*', 'logs')))
 
    apache = logApache()
    try:
        apache.dirs = LOG_DIR
        apache.logrotate()
        apache.graceful()
        apache.logdelete()
    except Exception as e:
        raise