nginx log split for linux

  • 2020-05-06 12:16:21
  • OfStack

To use the method, save the following script as cutlog.sh, place it in the /root directory, and then give the script permission to execute


chmod +x cutlog.sh

Then add this script to the scheduled task using crontab-e,


00 00 * * * /bin/bash /root/cutlog.sh

Let this script execute at 0 a.m. each day.


#!/bin/bash
#function:cut nginx log files shell
# Set up your site access log to save the directory that my uniform is placed in /home/wwwlogs directory 
log_files_path="/home/wwwlogs/"
log_files_dir=${log_files_path}$(date -d "yesterday" +"%Y")/$(date -d "yesterday" +"%m")
# Set what you want to cut nginx Log file name, such as the set log file name is 52listen.com.log  If so, fill it out here  52listen.com  Can be 
log_files_name=(52listen.com access)
# Set up the nginx The path to the execution file. 
nginx_sbin="/usr/local/nginx/sbin/nginx"
# Set the number of log days you want to save 30 Day before log 
save_days=30
############################################
#Please do not modify the following script #
############################################
mkdir -p $log_files_dir
log_files_num=${#log_files_name[@]}
#cut nginx log files
for((i=0;i<$log_files_num;i++));do
mv ${log_files_path}${log_files_name[i]}.log ${log_files_dir}/${log_files_name[i]}_$(date -d "yesterday" +"%Y%m%d").log
done
#delete 30 days ago nginx log files
find $log_files_path -mtime +$save_days -exec rm -rf {} \;
$nginx_sbin -s reload


Related articles: