Adding shell scripts under Linux allows nginx logs to be cut and compressed every day
A Brief introduction
For nginx log files, especially the access log, if we do not do any processing, the final file will become very large
At this point, it can be cumbersome to check the log when an exception occurs, or to analyze the log using tools such as "goaccess". Therefore, it is necessary to cut and compress the Nginx log regularly every day.
Two implementations
My idea is to execute the script at the close of 12 o ' clock every night. The script content is to rename the current Nginx log according to the date of the day and then compression, and finally the new blank nginx log file, and reload the Nginx
[Email protected] ~]# cd/usr/local
[Email protected] local]# mkdir scripts
[Email protected] scripts]# vim nginxlog.sh
The contents are as follows:
#!/bin/sh
cd/usr/local/nginx/logs/
newaccesslog= "Access ' date +%y-%m-%d '. Log"
newerrorlog= "error ' date +%y-%m-%d '. Log"
MV Access.log $newAccessLog
MV Error.log $newErrorLog
#创建日志文件
Touch Access.log Error.log
#reload Nginx
/etc/init.d/nginx Reload
#压缩日志文件
TAR-ZCVF $newAccessLog. tar.gz $newAccessLog--remove-files
TAR-ZCVF $newErrorLog. tar.gz $newErrorLog--remove-files
Add executable permissions to the script:
[Email protected] scripts]# chmod a+x nginxlog.sh
Add a scheduled task (performed 23:40 daily):
[Email protected] scripts]# cd/var/spool/cron/
[[email protected] cron]# echo "Max * * */usr/local/scripts/nginxlog.sh" > Root
To view tasks:
[Email protected] cron]# crontab-l
This way, you can see the effect the next day. The final effect is as follows:
Wkiom1g7jvtqihutaaaxvwvg1yi313.png
Note: If you have more than one nginx log file, consider changing my script to a more general form.
Attached: Nginx Log timer cleanup script:
[Email protected] scripts]# vim/usr/local/scripts/cleannginxlog.sh
The contents are as follows:
#!/bin/sh
cd/usr/local/nginx/logs/
Find. -name "* ' date-d ' -1months ' +%y-%m-%d ' *"-type f | Xargs-i {} rm-f {}
Note: The above script means to delete the log file for the day one months before the current day
Add executable permissions to the script:
[Email protected] scripts]# chmod a+x/usr/local/scripts/cleannginxlog.sh
Add a timed task (performed 0:30 daily):
[Email protected] scripts]# echo "0 * * */usr/local/scripts/cleannginxlog" >>/var/spool/cron/root
The above part from the network blog, I did some summary
Adding shell scripts under Linux allows nginx logs to be cut and compressed every day