python切割nginx日誌指令碼

2021-09-20 23:17:26 字數 2906 閱讀 7895

#!/usr/bin/env python

#-*-coding:utf-8-*-

#python nginx cut log 1

import subprocess

def mkdir():

subprocess.call('mkdir -pv /usr/local/nginx/logs/$(date -d "yesterday" +"%y")/$(date -d "yesterday" +"%m")/',shell=true)

def mv():

subprocess.call('mv /usr/local/nginx/logs/access.log /usr/local/nginx/logs/$(date -d "yesterday" +"%y")/$(date -d "yesterday" +"%m")/access_$(date -d "yesterda

y" +"%y%m%d").log',shell=true)

def kill():

pid = open("/usr/local/nginx/logs/nginx.pid","r")

f = pid.read()

f = f.strip()

pid.close()

kill = "kill"

kill_usage = "-usr1"

subprocess.call([kill,kill_usage,f])

def main():

mkdir()

mv()

kill()

if __name__ == "__main__":

main()

#!/usr/bin/env python

#-*-coding:utf-8-*-

#python nginx cut log 2

import time

import os

import datetime

path = ['/usr/local/nginx/logs','access.log','nginx.pid']

now_time = datetime.datetime.now()

yes_time = now_time + datetime.timedelta(days=-1)

yes_ymd = yes_time.strftime("%y%m%d")

yes_year = yes_time.strftime("%y")

yes_month = yes_time.strftime("%m")

command1 = "mkdir -pv %s/%s/%s" % (path[0],yes_year,yes_month)

command2 = "cd %s && mv %s %s/%s/%s/%s.log" % (path[0],path[1],path[0],yes_year,yes_month,yes_ymd)

command3 = "kill -usr1 `cat %s/%s`" % (path[0],path[2])

if os.system(command1) == 0:

print "目錄生成成功!"

else:

print "目錄生成失敗!"

if os.system(command2) == 0:

print "日誌切割成功!"

else:

print "日誌切割失敗!"

if os.system(command3) == 0:

print "平滑重啟nginx成功!"

else:

print "平滑重啟nginx失敗!"

#!/usr/bin/env python

#-*-coding:utf-8-*-

#python nginx cut log 3

import time

import os

import datetime

import shutil

#path列表存入路徑和檔案

path = ['/usr/local/nginx/logs','access.log','nginx.pid']

now_time = datetime.datetime.now()      #現在時間

yes_time = now_time + datetime.timedelta(days=-1)       #昨天的時間

yes_ymd = yes_time.strftime("%y%m%d")   #格式化輸出昨天的年月日

yes_year = yes_time.strftime("%y")      #格式化輸出昨天的年份

yes_month = yes_time.strftime("%m")     #格式化輸出昨天的月份

#建立備份目錄

path_back = "%s/%s/%s/" % (path[0],yes_year,yes_month)

if os.path.exists(path_back) == false :

os.makedirs(path_back)

#移動日誌至備份目錄下

file_now = "%s/%s" % (path[0],path[1])

file_back = "%s/%s/%s/%s.log" % (path[0],yes_year,yes_month,yes_ymd)

shutil.move(file_now,file_back)

#重置nginx日誌

pid_path = "%s/%s" % (path[0],path[2])

f = open(pid_path)

pid = f.readline()

pid = pid.strip()

command = "kill -usr1 %s" % pid

os.system(command)

f.close()

Python切割nginx日誌

前面寫過bash shell對nginx日誌的切割,現在用python進行其操作。usr bin python coding utf 8 created on 2011 11 17 切割nginx的日誌檔案,重新生成乙個log日誌,nginx的程序號不變動 author jimingsong imp...

nginx日誌切割

web 訪問日誌 access log 記錄了所有外部客戶端對web伺服器的訪問行為,包含了客戶端ip,訪問日期,訪問的url資源,伺服器返回的http狀態碼等重要資訊。一條典型的web訪問日誌如下 規劃 1 要解決問題 2 nignx沒有自動分開檔案儲存日誌的機制。由於nginx它不會幫你自動分檔...

nginx 日誌切割

直接在nginx配置檔案中,配置日誌迴圈,而不需使用logrotate或配置cron任務。需要使用到 time iso8601 內嵌變數來獲取時間。time iso8601格式如下 2015 08 07t18 12 02 02 00。然後使用正規表示式來獲取所需時間的資料。使用下面的 塊 1 2 3...