日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python 日志不会按照日期分割_python日志切割保留一个月

發布時間:2025/3/15 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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日志切割保留一个月的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。