python监控日志并予以清理

来源:互联网 发布:d3.js demo 编辑:程序博客网 时间:2024/05/01 10:59

Daemonize.py 

importos
importsys
 
classDaemonize:
    defdaemonize(self):
        try:
            pid=os.fork()
            ifpid > 0:
                sys.exit(0)
        exceptOSError,e:
            sys.stderr.write("Fork 1 has failed --> %d--[%s]\n" \
                             %(e.errno,e.strerror))
            sys.exit(1)
 
        os.chdir('/')
        #detach from terminal
        os.setsid()
        #file to be created?
        os.umask(0)
 
        try:
            pid=os.fork()
            ifpid > 0:
                print"Daemon process pid %d" % pid
                sys.exit(0)
        exceptOSError, e:
            sys.stderr.write("Fork 2 has failed --> %d--[%s]" \
                             %(e.errno, e.strerror))
            sys.exit(1)
 
        sys.stdout.flush()
        sys.stderr.flush()
 
    defstart_daemon(self):
        self.daemonize()
        self.run_daemon()
 
    defrun_daemon(self):
        '''override'''
        pass
    

watchLog.py

importos
importsmtplib
fromsmtplib importSMTPException
importtime
 
fromDaemonize importDaemonize
 
fromsubprocess importPopen
 
LOG_PATH=''
LOG_FILENAME=''
 
classWatchLog(Daemonize):
 
    def__init__(self, file_path, size_limit=15728640):
        self.file= os.path.realpath(file_path)
        printself.file
        print'---'
        assertos.path.isfile(self.file),'%s does not exist' % self.file
        print'+++'
        self.smtpserver="path to your host"
        self.recipient_list=['@gmail.com']
        self.sender='@'
        self.file_size_limit=size_limit
        self.email_body="path to your email tempalte"
 
    defsend_an_email(self):
 
        email_body=open(self.email_body,'r').read()
        session_obj=smtplib.SMTP(self.smtpserver)
        try:
            session_obj.sendmail(self.sender,self.recipient_list, email_body)
        exceptSMTPException:
            print"unable to send emails"
        finally:
            session_obj.close()
             
    defdelFile(self):
        os.chdir(LOG_PATH)
        cmd="echo '' > " + LOG_FILENAME
        try:
            Popen(cmd, shell=True)
        exceptException,e:
            printe
 
    defwatch(self):
        current_file_size=os.path.getsize(self.file)
        ifcurrent_file_size > self.file_size_limit:
            self.defFile()
             
    defrun_daemon(self):#override
        whileTrue:
            self.watch()
            time.sleep(3600)
 
if__name__ =="__main__":
    watchdog=WatchLog(LOG_PATH+LOG_FILENAME)
    watchdog.start_daemon()



0 0
原创粉丝点击