通过python编写定时任务压缩日志文件

来源:互联网 发布:linux sshd服务是什么 编辑:程序博客网 时间:2024/06/05 18:37

1.  定时任务使用的是APScheduler 框架, 使用本例前需安装APScheduler。 具体安装可参考我的《CentOS python2.6.6 升级 2.7.5 并安装pip, apscheduler》 这篇文章。

2. 不多说,直接上代码了。

#coding=utf-8#from apscheduler.schedulers.blocking import BlockingSchedulerimport datetimeimport timeimport osimport zipfile  import logginglogging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S',filename='myapp.log',filemode='w')#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#console = logging.StreamHandler()console.setLevel(logging.INFO)formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')console.setFormatter(formatter)logging.getLogger('').addHandler(console)root_path = "/usr/local/apache-tomcat/logs/"def zip_files(zip_src): logging.info( "begin zip ...")if(os.path.exists(root_path+zip_src) == False):logging.info( zip_src+" not found")returnf = zipfile.ZipFile(root_path+zip_src+".zip", 'w' ,zipfile.ZIP_DEFLATED)   f.write(root_path+zip_src)  f.close()  logging.info( "zip "+zip_src+" done")os.remove(root_path+zip_src)    def tick():logging.info('Tick! The time is: %s' % datetime.datetime.now())  now = datetime.datetime.now()delta = datetime.timedelta(days=-1) #获取前一天的日期n_days = now + deltayestoday = n_days.strftime('%Y-%m-%d')catalina_out = "catalina."+yestoday+".out"zip_files(catalina_out)if __name__ == '__main__':scheduler = BlockingScheduler()scheduler.add_job(tick,'cron', hour='2')    #每天两点执行#print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C'))try:scheduler.start()except (KeyboardInterrupt, SystemExit):scheduler.shutdown() 
3. nohup python compressLog.py >my.log &  通过该命令使python程序后台运行

阅读全文
0 0
原创粉丝点击