python 日志不会按照日期分割_python日志切割保留一个月
公司的nginx日志都放在一個文件里,時間長了,日志也變的很大,查起來也很不方便,所以決定將nginx的日志切割下,當然日志切割用shell寫更方便,但為了讓自己多實踐下python,故用python來實現。日志切割需求:每天切割nginx日志,保留一個月的即可。以下是具體實現方法。
#!/usr/bin/env python
# coding=utf-8
# author:xupeng(xupeng.js@gmail.com)
# Description:nginx日志切割腳本
# Usage crontab: 59 23 * * * python /path/logcron.py
import os
import glob
import time
import shutil
#日志路徑
path = '/htdocs/logs'
#切割后日志路徑
cut_path = '/htdocs/cutlogs'
#nginx pid
nginx_pid = '/usr/local/nginx/nginx.pid'
#刪除之前一個月的日志目錄
year = int(time.strftime("%Y", time.localtime()))
month = int(time.strftime("%m", time.localtime()))
if (month == 1):
year = year - 1
month = 12
else:
month = month - 1
year = str(year)
month = str(month)
if (len(month) == 1):
month = '0' + month
olddir = cut_path +'/' + year + month
if os.path.exists(olddir):
shutil.rmtree(olddir)
#創建目錄
cut_path = cut_path + '/' + str(time.strftime("%Y%m", time.localtime())) + '/'
if not os.path.exists(cut_path):
os.makedirs(cut_path)
#切割日志目錄下的日志
files = glob.glob("%s/*.log"%(path))
for sfile in files:
filearr = sfile.split('.')
filename = filearr[0]
filename = filename.split(path)
filename = filename[1].replace('/', '')
newfilename = cut_path + filename + '_' + str(time.strftime("%Y%m%d", time.localtime())) + '.log'
#print newfilename
os.system("mv %s %s"%(sfile,newfilename))
#重新打開日志文件
os.system("kill -s USR1 `cat %s`"%(nginx_pid))
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python 日志不会按照日期分割_python日志切割保留一个月的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 扫盲-我说云计算
- 下一篇: 退出python交互模式_python如