Detailed explanation of the implementation process of Nginx log timing splitting in CentOS 7

  • 2021-08-17 01:25:51
  • OfStack

1. Write a split script (splitNginxLog. sh)

* Because the log is split at 0 o'clock every day in this example, both folder and rq are set to use yesterday's date for archiving.


#!/bin/bash
folder=`date -d yesterday +%Y%m`
rq=`date -d yesterday +%Y%m%d`
#  Original log path 
logs_path="/var/log/nginx/sitename.com/"
#  Log backup path 
logs_backup_path="/var/log/nginx/sitename.com/$folder"
#  Log to partition 
logs_access="access"
logs_error="error"
#  Create a backup path 
[ -d $logs_backup_path ]||mkdir -p $logs_backup_path
#  Move the log to the backup folder 
mv ${logs_path}${logs_access}.log ${logs_backup_path}/${logs_access}_${rq}.log
mv ${logs_path}${logs_error}.log ${logs_backup_path}/${logs_error}_${rq}.log
#  Terminate nginx Adj. pid
pid_path="/var/run/nginx.pid"
kill -USR1 $(cat $pid_path)

2. Test the log splitting script

Run the following statement in the directory where the. sh file is stored to test whether the split script is successful.

# sh splitNginxLog.sh

If the prompt $'\ r': No resolution to the command is found, there may be a. sh file encoding problem because the scripts written in the Windows editor are somewhat different from those in linux.

Treatment method:

1. Install dos2unix for conversion coding

# yum install dos2unix   

2. Transcoding

# dos2unix splitNginx.sh   

3. Set timer auto-execution

# crontab-l//Lists all timed tasks
# crontab-e//Edit Timing Task

Write the following statement in it:

00 00 * * * bash /root/splitNginxLog.sh


Related articles: