Nginx 日誌檔案切割

2021-08-28 22:16:09 字數 2581 閱讀 4229

阿里雲的nginx好久沒檢視過日誌,現在需要配置定時任務實現,日誌檔案切割,並刪除超過30天的日誌檔案。

log.sh

指令碼檔案

#!/bin/bash

#獲取當前時間 yyyy-mm-dd_hh_mm_ss 格式

nowtime=`date "+%y-%m-%d_%h_%m_%s"`

cd /usr/local/nginx

mv logs/error.log ./logbak/$_error.log

mv logs/access.log ./logbak/$_access.log

nginx -s reopen # 執行者條語句 ,確認 nginx 命令的位置

# 上面也可以用 kill -usr1 $(cat /usr/local/nginx/logs/nginx.pid)

# 刪除30之氣的檔案

find /usr/local/nginx/logbak -ctime +30 -type f | xargs rm -rf

crontab -e來新增定時任務

00 04 1 * *  /usr/local/nginx/log.sh
[root@centos64 logs]# crontab -u grq

crontab: usage error: file name must be specified for replace

usage:

crontab [options] file

crontab [options]

crontab -n [hostname]

#定時任務選項,如果不指定使用者,則表示當前登入的使用者

options:

-u define user

-e edit user's crontab

-l list user's crontab

-r delete user's crontab

-i prompt before deleting

-n set host in cluster to run users' crontabs

-c get host in cluster to run users' crontabs

-s selinux context

-x enable debugging

-----------------------------------------

[root@centos64 logs]# more /etc/crontab

shell=/bin/bash

path=/sbin:/bin:/usr/sbin:/usr/bin

mailto=root

# for details see man 4 crontabs

# example of job definition:

# .---------------- minute (0 - 59)分

# | .------------- hour (0 - 23)時

# | | .---------- day of month (1 - 31)日

# | | | .------- month (1 - 12) or jan,feb,mar,apr ...月

# | | | | .---- day of week (0 - 6) (sunday=0 or 7) or sun,mon,tue,wed,thu,fri,sat周

# | | | | |

# * * * * * user-name command to be executed

[root@centos64 logs]#

#只保留30之內檔案,其餘檔案刪除

find /usr/local/nginx/logbak -mtime +30 -type f -name *.log -exec rm -rf {} \;

/usr/local/nginx/logbak --設定查詢的目錄;

-mtime +30 --設定時間為30天前;

-type f --設定查詢的型別為檔案;

-name *.log --設定檔名稱中包含mail1或者mail2;

-exec rm -f --查詢完畢後執行刪除操作;

find . -ctime +40 -type f | xargs rm -rf
上述兩者比較

兩者都可以把find命令查詢到的結果刪除,其區別簡單的說是前者是把find發現的結果一次性傳給exec選項,這樣當檔案數量較多的時候,就可能會出現「引數太多」之類的錯誤,相比較而言,後者就可以避免這個錯誤,因為xargs命令會分批次的處理結果。這樣看來,「find ./| xargs rm -rf」是更通用的方法,推薦使用!

linux shell 獲取格式化時間

定時任務

刪除檔案2種方法比較

nginx 切割日誌檔案

1.首先編寫shell指令碼 cutlog.sh 放入nginx logs資料夾中 首先定義路徑變數 logs path usr local nginx logs 獲取昨天的 yyyy mm dd d date y m d 移動檔案 mv access.log log 向 nginx 主程序傳送 u...

nginx日誌檔案切割

建立指令碼logcut.sh,放到 opt nginx sbin下 在windows下編輯,可以把dos轉unix格式 bin bash 零點執行該指令碼 nginx 日誌檔案所在的目錄 logs path opt nginx logs 獲取昨天的 yyyy mm dd yesterday date...

nginx日誌切割

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