实例1:对jumpserver日志进行切割
[root@test-vm01 mnt]# cat log_rotate.py
#!/usr/bin/env python
import datetime,os,sys,shutil
log_path = '/opt/jumpserver/logs/'
log_file = 'jumpserver.log'
yesterday = (datetime.datetime.now() - datetime.timedelta(days = 1))
try:
os.makedirs(log_path + yesterday.strftime('%Y') + os.sep + \
yesterday.strftime('%m'))
except OSError,e:
print
print e
sys.exit()
shutil.move(log_path + log_file,log_path \
+ yesterday.strftime('%Y') + os.sep \
+ yesterday.strftime('%m') + os.sep \
+ log_file + '_' + yesterday.strftime('%Y%m%d') + '.log')
os.popen("sudo /opt/jumpserver/service.sh restart")
手动执行这个脚本:
[root@test-vm01 mnt]# chmod 755 log_rotate.py
[root@test-vm01 mnt]# python log_rotate.py
查看日志切割后的效果:
[root@test-vm01 mnt]# ls /opt/jumpserver/logs/
2017 jumpserver.log
[root@test-vm01 mnt]# ls /opt/jumpserver/logs/2017/
09
[root@test-vm01 mnt]# ls /opt/jumpserver/logs/2017/09/
jumpserver.log_20170916.log
然后做每日的定时切割任务:
[root@test-vm01 mnt]# crontab -e
30 1 * * * /usr/bin/python /mnt/log_rotate.py > /dev/null 2>&1
--------------------------------------------------------------------------------------
实例2:对nginx日志进行切割
[root@test-vm01 mnt]# vim log_rotate.py
#!/usr/bin/env python
import datetime,os,sys,shutil
log_path = '/app/nginx/logs/'
log_file = 'www_access.log'
yesterday = (datetime.datetime.now() - datetime.timedelta(days = 1))
try:
os.makedirs(log_path + yesterday.strftime('%Y') + os.sep + \
yesterday.strftime('%m'))
except OSError,e:
print
print e
sys.exit()
shutil.move(log_path + log_file,log_path \
+ yesterday.strftime('%Y') + os.sep \
+ yesterday.strftime('%m') + os.sep \
+ log_file + '_' + yesterday.strftime('%Y%m%d') + '.log')
os.popen("sudo kill -USR1 `cat /app/nginx/logs/nginx.pid`")
--------------------------------------------------------------------------------------
其他业务日志的切割脚本跟上面做法相同