Crontab和Shell腳本切割Nginx日志使用詳解
一、配置 Crontab 定時任務(wù)
- 配置文件路徑:
/var/spool/cron/root
- 添加定時任務(wù)
59 23 * * * /root/app/shell/nginx-log-slice.sh
配置解釋:在 每天的23時59分 執(zhí)行 /root/app/shell/nginx-log-slice.sh
腳本。
配置其他自定義時間可以參考:Linux強大的定時任務(wù)-Crontab,有詳細的配置說明。
二、編寫 shell 腳本
- 文件路徑:
/root/app/shell/nginx-log-slice.sh
nginx-log-slice.sh
完整代碼
#!/bin/bash . /etc/profile source /etc/profile source ~/.bash_profile PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin # 當(dāng)發(fā)生錯誤時中止腳本 set -e base="/usr/local/nginx/logs/" day="`date '+%Y%m%d'`" curDir="${base}${day}" accessLog=${base}access.log errorLog=${base}error.log ms="`date '+%s'`" # 判斷以當(dāng)天日期為名的文件夾是否存在,存在打印輸出,不存在就創(chuàng)建 if [ -d ${curDir} ];then echo "${curDir} 文件夾存在" else echo "${curDir} 文件夾不存在" mkdir ${curDir} fi # 復(fù)制當(dāng)前的 access.log 和 error.log 日志文件,文件名加上時間戳,并存入以當(dāng)天日期為名的文件夾 \cp -rf ${accessLog} ${curDir}/access-${ms}.log \cp -rf ${errorLog} ${curDir}/error-${ms}.log # 復(fù)制完成后清空原本的 access.log 和 error.log 日志文件 > ${accessLog} > ${errorLog} # 輸出成功或失敗的信息 if [ $? == 0 ]; then echo "nginx slice 成功 (${curDir}/access-${ms}.log)" else echo "nginx slice 失敗 (${curDir}/access-${ms}.log)" fi
三、遇到的問題
問題:crontab 定時任務(wù)執(zhí)行 shell 腳本時,可能遇到這種報錯:/bin/sh: /root/app/shell/nginx-log-slice.sh: Permission denied
,這就說明 shell 腳本權(quán)限不足。
解決:執(zhí)行以下命令為 nginx-log-slice.sh
文件授權(quán)。
chmod 777 /root/app/shell/nginx-log-slice.sh
使用 ll
命令查看文件權(quán)限
cd /root/app/shell ll
在授權(quán)前會輸出:
[root@VM-8-12-centos shell]# ll 總用量 8 -rwxrwxrwx 1 root root 404 10月 15 2021 test.sh -rw-r--r-- 1 root root 610 10月 9 2022 nginx-log-slice.sh
在授權(quán)后會輸出:
[root@VM-8-12-centos shell]# ll 總用量 8 -rwxrwxrwx 1 root root 404 10月 15 2021 test.sh -rwxrwxrwx 1 root root 610 10月 9 2022 nginx-log-slice.sh
一切就緒后建議執(zhí)行 nginx -s reload
重啟 Nginx 服務(wù)
以上就是Crontab和Shell腳本切割Nginx日志的詳細內(nèi)容,更多關(guān)于Crontab Shell切割Nginx的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
nginx代理webSocket鏈接,webSocket頻繁斷開重連方式
當(dāng)使用Nginx代理WebSocket連接時,若60秒內(nèi)無數(shù)據(jù)交互,連接會斷開,解決辦法包括增加proxy_read_timeout時長或在客戶端添加心跳機制,以維持連接穩(wěn)定2024-09-09linux設(shè)置Nginx自動重啟的實現(xiàn)
在Linux系統(tǒng)中,設(shè)置Nginx服務(wù)開機自動啟動及意外停止后自動重啟是保持服務(wù)穩(wěn)定運行的關(guān)鍵步驟,本文詳細介紹了如何使用systemctl命令和配置systemd服務(wù)文件來實現(xiàn)這一功能,感興趣的可以了解一下2024-09-09nginx實現(xiàn)數(shù)據(jù)庫端口轉(zhuǎn)發(fā)
本文主要介紹了nginx實現(xiàn)數(shù)據(jù)庫端口轉(zhuǎn)發(fā),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-03-03